DLSS 5 Neural Rendering for Images & Video with Frame Generation, RTX Video Super Resolution, HDR, and Color Grading
TypeScript ai-upscalingdlssdlss-5dlss5dlssgframe-generationframe-interpolationimage-enhancementimage-upscalingneural-renderingnvidianvidia-dlss-5nvidia-rtxrtx-videortx-video-super-resolutionvideo-enhancementvideo-upscaling
Add files via upload
Merserkc45c22d0837d
diff --git a/THIRD-PARTY-NOTICES b/THIRD-PARTY-NOTICES.txtsimilarity index 100%rename from THIRD-PARTY-NOTICESrename to THIRD-PARTY-NOTICES.txtdiff --git a/app.py b/app.pyindex 0d25e6f..156549d 100644--- a/app.py+++ b/app.py@@ -2,6 +2,12 @@ from __future__ import annotationsimport sys+sys.dont_write_bytecode = True++from src.portable import configure_portable_environment++configure_portable_environment()+from src.desktop.app import launch_desktopdiff --git a/cli.py b/cli.pynew file mode 100644index 0000000..c354be1--- /dev/null+++ b/cli.py@@ -0,0 +1,14 @@+"""Console entry point used by VE_CLI.exe and the bundled Python runtime."""+import sys++sys.dont_write_bytecode = True++from src.portable import configure_portable_environment++configure_portable_environment()++from src.cli.main import main+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/src/cli/__init__.py b/src/cli/__init__.pynew file mode 100644index 0000000..0fa88dc--- /dev/null+++ b/src/cli/__init__.py@@ -0,0 +1,3 @@+"""Headless Visual Enhancer command-line interface."""++VERSION = "1.0.0"diff --git a/src/cli/__main__.py b/src/cli/__main__.pynew file mode 100644index 0000000..774cc25--- /dev/null+++ b/src/cli/__main__.py@@ -0,0 +1,3 @@+from .main import main++raise SystemExit(main())diff --git a/src/cli/main.py b/src/cli/main.pynew file mode 100644index 0000000..a2c0823--- /dev/null+++ b/src/cli/main.py@@ -0,0 +1,487 @@+"""Small CLI surface over the application's existing processing workflow.++Only the standard library is imported at startup. Help and version work without+initializing Qt, GPU engines, logs, or application settings.+"""+from __future__ import annotations++import argparse+from contextlib import contextmanager, redirect_stdout+from dataclasses import replace+import glob+import json+import math+import os+from pathlib import Path+import re+import signal+import sys+import time+import traceback++from . import VERSION+from .progress import ConsoleProgress++IMAGE_FORMATS = {"png": "PNG", "jpg": "JPEG", "jpeg": "JPEG", "webp": "WebP",+ "avif": "AVIF", "tif": "TIFF", "tiff": "TIFF"}+VIDEO_CODECS = {"h264": "H.264", "hevc": "H.265", "av1": "AV1",+ "prores": "ProRes HQ", "ffv1": "FFV1 Lossless RGB 10-bit"}+QUALITIES = {"auto": "Auto (Default)", "good": "Good", "best": "Best", "max": "Max"}+DLSS_MODES = {"dlaa": "DLAA", "quality": "Quality", "balanced": "Balanced",+ "performance": "Performance", "ultra-performance": "Ultra Performance"}+++class UsageError(ValueError):+ """Invalid arguments or configuration; exit status 2."""+++class Parser(argparse.ArgumentParser):+ def error(self, message):+ raise UsageError(message)+++def finite_float(value):+ try:+ result = float(value)+ except ValueError as exc:+ raise argparse.ArgumentTypeError("expected a number") from exc+ if not math.isfinite(result):+ raise argparse.ArgumentTypeError("expected a finite number")+ return result+++def dimensions(value):+ match = re.fullmatch(r"(\d+)[xX](\d+)", value)+ if not match or not all(2 <= int(v) <= 16384 for v in match.groups()):+ raise argparse.ArgumentTypeError("use WIDTHxHEIGHT, with each dimension from 2 to 16384")+ return tuple(int(v) for v in match.groups())+++def build_parser():+ parser = Parser(prog="VE_CLI.exe", description="Visual Enhancer for images and videos, from your terminal.",+ epilog="Run VE_CLI.exe COMMAND --help for options. Advanced settings: export a JSON preset from the app.")+ parser.add_argument("--version", action="version", version=f"Visual Enhancer CLI {VERSION}")+ commands = parser.add_subparsers(dest="command", metavar="COMMAND")+ descriptions = {+ "render": "Enhance images or videos with Neural Rendering or a GUI pipeline preset.",+ "upscale": "Upscale images or videos with RTX Super Resolution or DLSS.",+ "interpolate": "Increase video frame rate with DLSS Frame Generation.",+ }+ for name, description in descriptions.items():+ command = commands.add_parser(name, help=description, description=description)+ command.add_argument("inputs", nargs="+", metavar="INPUT", help="files, folders, or quoted wildcards")+ command.add_argument("-o", "--output", metavar="PATH", help="output folder, or output filename for one input (default: app's outputs folder)")+ command.add_argument("--preset", metavar="JSON", help="settings preset exported from the app; flags override its values")+ command.add_argument("--recursive", action="store_true", help="include subfolders when scanning input folders")+ command.add_argument("--gpu", metavar="ID", help="AI/video GPU: auto, NVIDIA index, or GPU UUID (see devices)")+ if name != "interpolate":+ command.add_argument("--format", choices=("png", "jpeg", "webp", "avif", "tiff"), help="image output format (default: PNG or preset value)")+ command.add_argument("--codec", choices=tuple(VIDEO_CODECS), help="video codec (default: command/preset value)")+ command.add_argument("--container", choices=("mp4", "mkv", "mov"), help="supported video container (default: command/preset value)")+ command.add_argument("--quality", choices=tuple(QUALITIES), help="video encoding quality (default: auto or preset value)")+ command.add_argument("--dry-run", action="store_true", help="show planned inputs, stages and output sizes without rendering")+ command.add_argument("--quiet", action="store_true", help="hide progress; keep errors and the final result")+ command.add_argument("--json", action="store_true", help="write one JSON result to stdout; progress/errors go to stderr")+ if name == "render":+ command.add_argument("--style", choices=("default", "natural", "cinematic"), help="Neural Rendering style (default: default or preset value)")+ command.add_argument("--strength", type=finite_float, metavar="0..2", help="Neural Rendering intensity (default: 1 or preset value)")+ elif name == "upscale":+ command.add_argument("--engine", choices=("rtx", "dlss"), help="upscaling engine (default: rtx or preset value)")+ size = command.add_mutually_exclusive_group()+ size.add_argument("--scale", type=finite_float, metavar="FACTOR", help="RTX scale factor, at least 1 (default: 2 or preset value)")+ size.add_argument("--size", type=dimensions, metavar="WIDTHxHEIGHT", help="RTX output dimensions; uses the exact size")+ command.add_argument("--mode", choices=tuple(DLSS_MODES), help="DLSS mode (default: quality or preset value); controls output size")+ else:+ command.add_argument("--fps", metavar="FPS", help="target frame rate (default: 60 or preset value; e.g. 59.94, 120, 240)")+ devices = commands.add_parser("devices", help="List NVIDIA GPUs and IDs for --gpu.", description="List NVIDIA GPUs and IDs for --gpu.")+ devices.add_argument("--json", action="store_true", help="write GPU information as JSON")+ return parser+++def media_mode(path):+ from ..core.disk_paths import supported_file++ if supported_file(path, "image"):+ return "Image"+ if supported_file(path, "video"):+ return "Video"+ return None+++def collect_inputs(values, *, recursive=False, exclude=None):+ paths, seen = [], set()+ excluded = Path(exclude).resolve() if exclude else None+ for value in values:+ if not value.strip():+ raise UsageError("Input path cannot be empty.")+ path = Path(value).expanduser()+ literal = path.exists()+ matches = [path] if literal else [Path(p) for p in sorted(glob.glob(str(path), recursive=recursive))]+ if not matches:+ raise UsageError(f"Input does not exist or wildcard matched no files: {value}")+ accepted = 0+ for match in matches:+ if match.is_dir():+ root = match.resolve()+ if not literal and excluded and root.is_relative_to(excluded):+ continue+ files = match.rglob("*") if recursive else match.iterdir()+ candidates = sorted((p for p in files if p.is_file()), key=lambda p: (str(p).casefold(), str(p)))+ candidates = [p for p in candidates if not (excluded and excluded != root and p.resolve().is_relative_to(excluded))]+ elif match.is_file():+ candidates = [match]+ if not media_mode(match):+ if literal:+ raise UsageError(f"Unsupported image/video input: {match}")+ continue+ if not literal and excluded and match.resolve().is_relative_to(excluded):+ continue+ else:+ raise UsageError(f"Input is not a file or folder: {match}")+ for candidate in candidates:+ if not media_mode(candidate):+ continue+ accepted += 1+ resolved = candidate.resolve()+ key = os.path.normcase(str(resolved))+ if key not in seen:+ seen.add(key)+ paths.append(resolved)+ if not accepted:+ raise UsageError(f"No supported images or videos found: {value}")+ return paths+++def selected_gpu(value):+ from ..core.gpu_detection import detect_gpus++ if value.casefold() == "auto":+ return "auto"+ for gpu in detect_gpus():+ if value.casefold() in {str(gpu["index"]), gpu["uuid"].casefold()}:+ if not gpu["ai_compatible"]:+ raise UsageError(f"{gpu['name']} cannot run RTX processing. {gpu['compatibility_error']}")+ return gpu["uuid"]+ raise UsageError(f"Unknown GPU: {value}. Run VE_CLI.exe devices for available IDs.")+++def settings_for(args, modes):+ from ..core.ffmpeg import container_for_codec, containers_for_codec+ from ..settings.models import UISettings, _validate+ from ..settings.presets import import_settings_preset++ base = replace(UISettings(), image_rename_mode="Copy", video_rename_mode="Copy",+ upscale_image_rename_mode="Copy", upscale_rename_mode="Copy",+ frame_interpolation_rename_mode="Copy")+ try:+ settings = import_settings_preset(Path(args.preset).expanduser().resolve(), base)[1] if args.preset else base+ if args.command == "render":+ if not args.preset:+ settings = replace(settings, image_enabled_stages=("neural_model",), video_enabled_stages=("neural_model",))+ changes = {}+ if args.style:+ changes["nr_style"] = args.style.title()+ if args.strength is not None:+ changes["nr_intensity"] = args.strength+ if changes and any("neural_model" not in (settings.image_enabled_stages if mode == "Image" else settings.video_enabled_stages) for mode in modes):+ raise UsageError("The preset disables Neural Rendering. Enable it in the preset before using --style or --strength.")+ settings = replace(settings, **changes)+ elif args.command == "upscale":+ image_engine = settings.upscale_image_engine+ video_engine = settings.upscale_engine+ if args.engine:+ image_engine = video_engine = "DLSS" if args.engine == "dlss" else "RTX Video Super Resolution"+ engines = [image_engine if mode == "Image" else video_engine for mode in modes]+ if any(engine == "DLSS" for engine in engines) and (args.scale is not None or args.size):+ raise UsageError("DLSS output size is set by --mode. --scale and --size require --engine rtx.")+ if args.mode and any(engine != "DLSS" for engine in engines):+ raise UsageError("--mode requires --engine dlss.")+ settings = replace(settings,+ image_enabled_stages=("dlss_super_resolution" if image_engine == "DLSS" else "super_resolution",),+ video_enabled_stages=("dlss_super_resolution" if video_engine == "DLSS" else "super_resolution",),+ upscale_image_engine=image_engine, upscale_engine=video_engine,+ image_format=settings.upscale_image_output_format, image_quality=settings.upscale_image_quality,+ codec=settings.upscale_codec, container=settings.upscale_container,+ quality=settings.upscale_quality, hdr_mode=False,+ image_rename_mode=settings.upscale_image_rename_mode, image_custom_suffix=settings.upscale_image_custom_suffix,+ video_rename_mode=settings.upscale_rename_mode, video_custom_suffix=settings.upscale_custom_suffix)+ if args.scale is not None:+ settings = replace(settings, upscale_image_size_mode="Scale factor", upscale_size_mode="Scale factor",+ upscale_image_scale_factor=args.scale, upscale_scale_factor=args.scale)+ if args.size:+ width, height = args.size+ settings = replace(settings, upscale_image_size_mode="Custom dimensions", upscale_size_mode="Custom dimensions",+ upscale_image_width=width, upscale_image_height=height, upscale_width=width, upscale_height=height,+ upscale_image_aspect_lock=False, upscale_aspect_lock=False)+ if args.mode:+ settings = replace(settings, upscale_image_dlss_mode=DLSS_MODES[args.mode], upscale_dlss_mode=DLSS_MODES[args.mode])+ else:+ if "Image" in modes:+ raise UsageError("interpolate accepts videos only. Use render or upscale for images.")+ settings = replace(settings, video_enabled_stages=("frame_generation",),+ frame_interpolation_target_fps=args.fps or settings.frame_interpolation_target_fps,+ codec=settings.frame_interpolation_codec, container=settings.frame_interpolation_container,+ quality=settings.frame_interpolation_quality, hdr_mode=settings.frame_interpolation_hdr_mode,+ video_rename_mode=settings.frame_interpolation_rename_mode,+ video_custom_suffix=settings.frame_interpolation_custom_suffix)+ changes = {}+ if getattr(args, "format", None):+ if "Image" not in modes:+ raise UsageError("--format is for image output. Use --container for video output.")+ changes["image_format"] = IMAGE_FORMATS[args.format]+ if args.codec or args.container or args.quality:+ if "Video" not in modes:+ raise UsageError("--codec, --container and --quality are video options; use --format for images.")+ if args.codec:+ changes["codec"] = VIDEO_CODECS[args.codec]+ if not args.container and settings.container not in containers_for_codec(changes["codec"]):+ changes["container"] = container_for_codec(changes["codec"])+ if args.container:+ changes["container"] = args.container.upper()+ if args.quality:+ changes["quality"] = QUALITIES[args.quality]+ if args.gpu:+ gpu_uuid = selected_gpu(args.gpu)+ changes.update(ai_gpu_uuid=gpu_uuid, video_gpu_uuid=gpu_uuid)+ return _validate(replace(settings, **changes))+ except ValueError as exc:+ raise UsageError(str(exc)) from exc+++def plan_outputs(paths, settings, output, args):+ from ..core.ffmpeg import resolve_container+ from ..core.naming import output_filename, unique_output_path+ from ..core.paths import OUTPUTS+ from ..neural_rendering.image.models import IMAGE_EXTENSIONS+ from ..settings.models import _validate++ target = Path(output).expanduser().resolve() if output else OUTPUTS+ explicit = bool(output and not target.is_dir() and target.suffix.lower()[1:] in {*IMAGE_FORMATS, "mp4", "mkv", "mov"})+ if target.exists() and not target.is_dir():+ raise UsageError(f"Output already exists: {target}. Choose another name.")+ if explicit:+ if len(paths) != 1:+ raise UsageError("An output filename requires exactly one input. Use an output folder for batches.")+ extension = target.suffix.lower()[1:]+ if media_mode(paths[0]) == "Image":+ if extension not in IMAGE_FORMATS:+ raise UsageError("Image input requires an image output filename.")+ if args.format and IMAGE_FORMATS[args.format] != IMAGE_FORMATS[extension]:+ raise UsageError("--format does not match the output filename extension.")+ settings = replace(settings, image_format=IMAGE_FORMATS[extension])+ else:+ if extension not in {"mp4", "mkv", "mov"}:+ raise UsageError("Video input requires an MP4, MKV or MOV output filename.")+ if args.container and args.container != extension:+ raise UsageError("--container does not match the output filename extension.")+ settings = replace(settings, container=extension.upper())+ try:+ settings = _validate(settings)+ except ValueError as exc:+ raise UsageError(str(exc)) from exc+ return settings, [target], target.parent+ reserved, destinations = set(), []+ stamp = time.strftime("%Y%m%d-%H%M%S")+ for source in paths:+ image = media_mode(source) == "Image"+ extension = IMAGE_EXTENSIONS[settings.image_format] if image else "." + resolve_container(+ settings.codec, settings.container).lower()+ filename = output_filename(source, extension,+ settings.image_rename_mode if image else settings.video_rename_mode,+ settings.image_custom_suffix if image else settings.video_custom_suffix,+ f"{source.stem}_Pipeline_{stamp}")+ destination = unique_output_path(target / filename, reserved)+ reserved.add(destination)+ destinations.append(destination)+ return settings, destinations, target+++@contextmanager+def cancellation_signals(controller):+ old = {}++ def cancel(_signum, _frame):+ # The processors poll this event and terminate their registered children.+ # Do not take the controller's process-list lock inside a signal handler.+ controller.cancel.set()++ try:+ for name in ("SIGINT", "SIGBREAK"):+ if hasattr(signal, name):+ sig = getattr(signal, name)+ old[sig] = signal.signal(sig, cancel)+ yield+ finally:+ for sig, handler in old.items():+ signal.signal(sig, handler)+++def dry_run(paths, destinations, settings):+ from ..core.ffmpeg import probe_video+ from ..desktop.workflow import enabled_stages, estimate_pipeline+ from ..neural_rendering.image.decoder import _open_pillow_source++ jobs = []+ for path, output in zip(paths, destinations):+ mode = media_mode(path)+ if mode == "Image":+ image, _ = _open_pillow_source(path)+ try:+ width, height = image.size+ if image.getexif().get(274) in {5, 6, 7, 8}:+ width, height = height, width+ finally:+ image.close()+ fps, hdr = 0.0, False+ else:+ metadata = probe_video(path, count_mode="metadata")+ width, height, fps, hdr = (int(metadata["width"]), int(metadata["height"]),+ float(metadata["fps"]), bool(metadata.get("hdr")))+ estimate = estimate_pipeline(width, height, fps, hdr, settings, mode)+ jobs.append({"input_path": str(path), "output_path": str(output), "media_type": mode.lower(),+ "stages": [*enabled_stages(settings, mode), "export"],+ "width": estimate.width, "height": estimate.height, "fps": estimate.fps, "hdr": estimate.hdr})+ return jobs+++def run_jobs(paths, destinations, settings, console):+ from ..core import app_log+ from ..core.batch_progress import BatchProgress+ from ..core.disk_paths import prepare_output_dir+ from ..core.jobs import Cancelled, JobController, use_job_controller+ from ..desktop.workflow import preflight_capabilities, render_item++ controller = JobController()+ reporter = BatchProgress(paths, console)+ capability_errors, checked = {}, set()+ started = time.monotonic()+ log_path = str(app_log.init_session())+ app_log.info("cli", f"start: {len(paths)} file(s)")+ try:+ with cancellation_signals(controller), use_job_controller(controller):+ for index, (source, destination) in enumerate(zip(paths, destinations)):+ if controller.cancel.is_set():+ break+ reporter.advance(index)+ mode = media_mode(source)+ try:+ if mode not in checked:+ try:+ preflight_capabilities(settings, mode, controller)+ except Exception as exc:+ capability_errors[mode] = exc+ checked.add(mode)+ if mode in capability_errors:+ raise capability_errors[mode]+ if controller.cancel.is_set():+ raise Cancelled("Stopped by user.")+ prepare_output_dir(destination.parent)+ rendered = render_item(source, settings, mode, destination, controller,+ lambda value, detail, i=index: reporter.advance(i, value, detail),+ capabilities_checked=True)+ reporter.complete(index, rendered)+ except Exception as exc:+ cancelled = isinstance(exc, Cancelled) or controller.cancel.is_set()+ reporter.fail(index, exc, cancelled=cancelled)+ app_log.fail("cli", f"cli-{time.time_ns()}", exc, {"traceback": traceback.format_exc()})+ if cancelled:+ controller.cancel.set()+ break+ if controller.cancel.is_set():+ reporter.skip_from(0)+ reporter.finish(cancelled=controller.cancel.is_set(), manifest_path=log_path)+ finally:+ controller.terminate_processes()+ console.finish()+ items = [{"input_path": item.input_path, "output_path": item.output_path,+ "state": item.state.lower(), "error": item.detail if item.state in {"Failed", "Cancelled"} else "",+ "elapsed_seconds": round(item.elapsed_seconds, 3)} for item in reporter.items]+ failed = sum(item.state == "Failed" for item in reporter.items)+ completed = sum(item.state == "Complete" for item in reporter.items)+ cancelled = controller.cancel.is_set()+ status = 130 if cancelled else 1 if failed else 0+ app_log.info("cli", f"done: {completed} completed, {failed} failed, cancelled={cancelled}")+ return status, {"total": len(paths), "completed": completed, "failed": failed,+ "skipped": sum(item.state == "Skipped" for item in reporter.items),+ "cancelled": cancelled, "elapsed_seconds": round(time.monotonic() - started, 3),+ "items": items, "log_path": log_path}+++def emit_error(message, *, status, json_output):+ if json_output:+ print(json.dumps({"schema_version": 1, "ok": False, "exit_code": status, "error": str(message)}, ensure_ascii=False))+ print(f"Error: {message}", file=sys.stderr)+ if status == 2 and not json_output:+ print("Run VE_CLI.exe COMMAND --help for usage.", file=sys.stderr)+ return status+++def main(argv=None):+ argv = list(sys.argv[1:] if argv is None else argv)+ parser = build_parser()+ json_output = "--json" in argv+ try:+ if not argv:+ parser.print_help()+ return 0+ try:+ args = parser.parse_args(argv)+ except SystemExit as exc:+ return int(exc.code or 0)+ if not args.command:+ raise UsageError("Choose a command: render, upscale, interpolate, or devices.")+ if args.command == "devices":+ from ..core.gpu_detection import detect_gpus++ gpus = list(detect_gpus())+ if json_output:+ print(json.dumps({"schema_version": 1, "ok": True, "devices": gpus}, ensure_ascii=False))+ else:+ for gpu in gpus:+ print(f"{gpu['index']} {gpu['name']} ({gpu['memory_mb'] / 1024:.1f} GB VRAM)")+ print(f" {gpu['uuid']} | Driver {gpu['driver']} | RTX processing: {'yes' if gpu['ai_compatible'] else 'unavailable'}")+ return 0+ from ..core.paths import OUTPUTS++ output = Path(args.output).expanduser().resolve() if args.output else OUTPUTS+ paths = collect_inputs(args.inputs, recursive=args.recursive, exclude=output)+ settings = settings_for(args, {media_mode(p) for p in paths})+ settings, destinations, folder = plan_outputs(paths, settings, args.output, args)+ if args.dry_run:+ try:+ jobs = dry_run(paths, destinations, settings)+ except (ValueError, OSError) as exc:+ raise UsageError(str(exc)) from exc+ result = {"schema_version": 1, "ok": True, "command": args.command, "dry_run": True, "total": len(paths), "items": jobs}+ if json_output:+ print(json.dumps(result, ensure_ascii=False))+ else:+ for index, job in enumerate(jobs):+ fps = f" | {job['fps']:g} FPS" if job["fps"] else ""+ print(f"[{index + 1}/{len(jobs)}] {job['input_path']}\n -> {job['output_path']}\n {job['width']}x{job['height']}{fps} | {' -> '.join(job['stages'])}")+ print("Plan only. Hardware availability is checked when rendering.")+ return 0+ from ..core import app_log++ console = ConsoleProgress(paths, sys.stderr, quiet=args.quiet)+ # Engine chatter belongs in the application log. stdout stays usable by+ # scripts, including when the shared engines emit diagnostic messages.+ with redirect_stdout(app_log.SessionStream()):+ status, result = run_jobs(paths, destinations, settings, console)+ result.update(schema_version=1, ok=status == 0, exit_code=status, command=args.command)+ if json_output:+ print(json.dumps(result, ensure_ascii=False))+ else:+ label = "Cancelled" if result["cancelled"] else "Completed"+ print(f"{label}: {result['completed']}/{result['total']} files in {result['elapsed_seconds']:.1f}s; {result['failed']} failed.")+ if result["completed"]:+ print(f"Output: {destinations[0] if len(paths) == 1 else folder}")+ if status:+ print(f"Log: {result['log_path']}")+ return status+ except UsageError as exc:+ return emit_error(exc, status=2, json_output=json_output)+ except KeyboardInterrupt:+ return emit_error("Stopped by user.", status=130, json_output=json_output)+ except Exception as exc:+ return emit_error(exc, status=1, json_output=json_output)diff --git a/src/cli/progress.py b/src/cli/progress.pynew file mode 100644index 0000000..2718799--- /dev/null+++ b/src/cli/progress.py@@ -0,0 +1,75 @@+"""Compact console progress, using the same whole-file updates as the desktop."""+from __future__ import annotations++import re+import shutil+import threading+import time+++class ConsoleProgress:+ def __init__(self, paths, stream, *, quiet=False):+ self.paths = paths+ self.stream = stream+ self.quiet = quiet+ self.interactive = bool(stream.isatty())+ self.last_print = 0.0+ self.current_index = None+ self.last_stage = ""+ self.line_open = False+ self.lock = threading.RLock()++ def _line(self, text):+ if self.line_open:+ self.stream.write("\r\033[2K")+ self.line_open = False+ self.stream.write(text + "\n")+ self.stream.flush()++ def __call__(self, update):+ with self.lock:+ if update.index is None:+ self.finish()+ return+ number = f"[{update.index + 1}/{len(self.paths)}]"+ name = self.paths[update.index].name+ if update.state in {"Failed", "Cancelled"}:+ self._line(f"{number} {update.state}: {name}: {update.detail}")+ elif update.state == "Complete":+ if not self.quiet:+ self._line(f"{number} Saved: {update.output_path}")+ elif update.state == "Running" and not self.quiet:+ match = re.search(r"\bStage (\d+) of (\d+)\b", update.detail)+ stage = f"Processing Stage {match[1]} of {match[2]}" if match else "Preparing"+ if self.current_index != update.index:+ self._line(f"{number} {name}")+ self.current_index = update.index+ self.last_stage = ""+ if not self.interactive:+ if stage != self.last_stage:+ self._line(f" {stage}")+ self.last_stage = stage+ return+ now = time.monotonic()+ if now - self.last_print < .15 and stage == self.last_stage:+ return+ self.last_print, self.last_stage = now, stage+ fraction = max(0.0, min(.99, update.progress))+ remaining = ""+ if update.elapsed_seconds >= 1 and fraction > .01:+ seconds = round(update.elapsed_seconds * (1 - fraction) / fraction)+ remaining = f" | ~{seconds // 60:02d}:{seconds % 60:02d} remaining"+ filled = int(fraction * 20)+ bar = "#" * filled + "-" * (20 - filled)+ text = f"{number} [{bar}] {fraction:.0%} | {stage}{remaining}"+ width = max(20, shutil.get_terminal_size((100, 25)).columns - 1)+ self.stream.write("\r\033[2K" + text[:width])+ self.stream.flush()+ self.line_open = True++ def finish(self):+ with self.lock:+ if self.line_open:+ self.stream.write("\n")+ self.stream.flush()+ self.line_open = Falsediff --git a/src/core/app_log.py b/src/core/app_log.pyindex 57cd9e9..5afc223 100644--- a/src/core/app_log.py+++ b/src/core/app_log.py@@ -50,6 +50,17 @@ def _redact(text: str) -> str:return re.sub(r"(https?://[^\s?]+)\?[^\s'\"]+", r"\1?<redacted>", text)+def record_batch_summary(kind: str, completed: int, failed: int,+ cancelled: bool, *, archive_error: str = "") -> str:+ """Write one batch result and return the shared session log path."""+ status = "cancelled" if cancelled else ("partial" if failed else "success")+ detail = f"{status} ok={completed} failed={failed}"+ if archive_error:+ detail += f" archive_warning={archive_error}"+ info(kind, detail)+ return session_path()++def sweep_old_sessions(days: int = RETENTION_DAYS) -> None:try:cutoff = time.time() - days * 86400diff --git a/src/core/cache_video.py b/src/core/cache_video.pynew file mode 100644index 0000000..4621692--- /dev/null+++ b/src/core/cache_video.py@@ -0,0 +1,41 @@+"""Video intermediate formats selected by Cache Memory settings."""+from __future__ import annotations+++CACHE_VIDEO_CODECS = ("FFV1", "ProRes Proxy")+++def cache_video_format(selection: str) -> tuple[str, str, str]:+ """Return the encoder's public codec name, container, and file suffix."""+ if selection == "FFV1":+ return "FFV1 Lossless RGB 10-bit", "MKV", ".mkv"+ if selection == "ProRes Proxy":+ return "ProRes Proxy", "MOV", ".mov"+ raise ValueError(f"Unknown cache video codec: {selection!r}.")+++def cache_ffmpeg_args(selection: str, metadata: dict) -> list[str]:+ """Encode a stage intermediate, preserving HDR signaling through ProRes."""+ if selection == "FFV1":+ args = ["-c:v", "ffv1", "-level", "3", "-pix_fmt", "gbrp10le"]+ for key, flag in (("color_primaries", "-color_primaries"),+ ("color_transfer", "-color_trc")):+ value = metadata.get(key)+ if value and value not in {"unknown", "unspecified"}:+ args.extend((flag, "0" if value == "gbr" else str(value)))+ return [*args, "-color_range", "pc"]+ if selection != "ProRes Proxy":+ raise ValueError(f"Unknown cache video codec: {selection!r}.")+ hdr = bool(metadata.get("hdr"))+ primaries = metadata.get("color_primaries")+ transfer = metadata.get("color_transfer")+ matrix = metadata.get("color_space")+ if primaries in {None, "", "unknown", "unspecified", "gbr"}:+ primaries = "bt2020" if hdr else "bt709"+ if transfer in {None, "", "unknown", "unspecified", "gbr"}:+ transfer = "smpte2084" if hdr else "bt709"+ if matrix in {None, "", "unknown", "unspecified", "gbr"}:+ matrix = "bt2020nc" if hdr else "bt709"+ return ["-c:v", "prores_ks", "-profile:v", "0", "-pix_fmt", "yuv422p10le",+ "-color_primaries", str(primaries), "-color_trc", str(transfer),+ "-colorspace", str(matrix), "-color_range", "tv"]diff --git a/src/core/ffmpeg/__init__.py b/src/core/ffmpeg/__init__.pyindex 3e317a5..bb69326 100644--- a/src/core/ffmpeg/__init__.py+++ b/src/core/ffmpeg/__init__.py@@ -1,30 +1,25 @@from .codecs import (- AUTO_BITRATE_DIVISORS, CODEC_CHOICES, ENCODING_QUALITIES, FIXED_QUALITY_CODECS, HDR_ALLOWED_CODECS,+ AUTO_BITRATE_DIVISORS, CODEC_CHOICES, CONTAINER_CHOICES, ENCODING_QUALITIES, FIXED_QUALITY_CODECS, HDR_ALLOWED_CODECS,_base_codec, _is_hdr_allowed_codec, _is_nvenc_codec, _normalize_codec,- calculate_auto_bitrate_kbps, container_for_codec, hdr_mode_supported, resolve_encoding_quality,+ calculate_auto_bitrate_kbps, container_for_codec, containers_for_codec, hdr_mode_supported, resolve_container, resolve_encoding_quality,validate_codec_container,)from .audio import AudioPlan, plan_audio_streamsfrom .encoder import probe_nvenc_codecs, resolve_video_gpu, start_encoderfrom .mux import final_mux, prepare_mux_comment, verify_mux_commentfrom .nut import RawVideoPacketMuxer-from .preview import (- DEFAULT_PREVIEW_ENCODING, PREVIEW_ENCODING_CHOICES, is_browser_playable,- is_user_playable_request, make_browser_preview, normalize_preview_encoding,- resolve_final_preview, resolve_preview_codec, wants_compat_preview,-)from .probe import preview_frame_count, probe_videofrom .precision import chroma_location_code, decoded_rgba, output_video_depth__all__ = [- "AUTO_BITRATE_DIVISORS", "AudioPlan", "CODEC_CHOICES", "DEFAULT_PREVIEW_ENCODING",- "ENCODING_QUALITIES", "FIXED_QUALITY_CODECS", "HDR_ALLOWED_CODECS", "PREVIEW_ENCODING_CHOICES",+ "AUTO_BITRATE_DIVISORS", "AudioPlan", "CODEC_CHOICES", "CONTAINER_CHOICES",+ "ENCODING_QUALITIES", "FIXED_QUALITY_CODECS", "HDR_ALLOWED_CODECS","RawVideoPacketMuxer", "calculate_auto_bitrate_kbps", "container_for_codec", "final_mux", "hdr_mode_supported",- "is_browser_playable", "is_user_playable_request", "make_browser_preview",- "normalize_preview_encoding", "plan_audio_streams", "prepare_mux_comment", "preview_frame_count", "probe_nvenc_codecs",- "probe_video", "resolve_encoding_quality", "resolve_final_preview",- "resolve_preview_codec", "resolve_video_gpu", "start_encoder",- "validate_codec_container", "verify_mux_comment", "wants_compat_preview",+ "plan_audio_streams", "prepare_mux_comment", "preview_frame_count", "probe_nvenc_codecs",+ "probe_video", "resolve_encoding_quality",+ "resolve_video_gpu", "start_encoder",+ "validate_codec_container", "verify_mux_comment","decoded_rgba", "output_video_depth","chroma_location_code",+ "containers_for_codec", "resolve_container",]diff --git a/src/core/ffmpeg/codecs.py b/src/core/ffmpeg/codecs.pyindex 90291de..0aae3f2 100644--- a/src/core/ffmpeg/codecs.py+++ b/src/core/ffmpeg/codecs.py@@ -1,269 +1,281 @@-from __future__ import annotations--import math--+from __future__ import annotations++import math++ENCODING_QUALITIES = ("Auto (Default)", "Max", "Best", "Good")--# User-facing codec choices: plain = CPU (libx264/libx265/libsvtav1), suffixed = NVIDIA NVENC.-CODEC_CHOICES = (- "H.264",- "H.264 (NVIDIA NVENC)",- "H.265",- "H.265 (NVIDIA NVENC)",- "AV1",- "AV1 (NVIDIA NVENC)",- "ProRes Proxy",- "ProRes HQ",- "FFV1 Lossless RGB 10-bit",-)--_CODEC_ALIASES = {- "HEVC": "H.265",- "H265": "H.265",- "H.265 (HEVC)": "H.265",- "HEVC (NVIDIA NVENC)": "H.265 (NVIDIA NVENC)",-}--_BASE_CODEC_MAP = {- "H.264": "H.264",- "H.264 (NVIDIA NVENC)": "H.264",- "H.265": "H.265",- "H.265 (NVIDIA NVENC)": "H.265",- "AV1": "AV1",- "AV1 (NVIDIA NVENC)": "AV1",- "ProRes Proxy": "ProRes Proxy",- "ProRes HQ": "ProRes HQ",- "FFV1 Lossless RGB 10-bit": "FFV1 Lossless RGB 10-bit",-}--_IS_NVENC_SET = {- "H.264 (NVIDIA NVENC)",- "H.265 (NVIDIA NVENC)",- "AV1 (NVIDIA NVENC)",-}--_NVENC_ENCODERS = {- "H.264 (NVIDIA NVENC)": "h264_nvenc",- "H.265 (NVIDIA NVENC)": "hevc_nvenc",- "AV1 (NVIDIA NVENC)": "av1_nvenc",-}--_AUTOMATIC_CONTAINERS = {- "H.264": "MP4",- "H.264 (NVIDIA NVENC)": "MP4",- "H.265": "MKV",- "H.265 (NVIDIA NVENC)": "MKV",- "AV1": "MKV",- "AV1 (NVIDIA NVENC)": "MKV",- "ProRes Proxy": "MOV",- "ProRes HQ": "MOV",- "FFV1 Lossless RGB 10-bit": "MKV",-}--# Keep AUTO_BITRATE_DIVISORS keyed by base codec; "HEVC" alias preserved for compat.-AUTO_BITRATE_DIVISORS = {- "H.264": 165_888,- "H.265": 331_776,- "HEVC": 331_776,- "AV1": 414_720,-}--# HDR Mode is only meaningful for 10-bit capable codecs. H.264 (both CPU/NVENC) stays 8-bit SDR.-HDR_ALLOWED_CODECS = {- "H.265",- "H.265 (NVIDIA NVENC)",- "AV1",- "AV1 (NVIDIA NVENC)",- "ProRes Proxy",- "ProRes HQ",- "FFV1 Lossless RGB 10-bit",-}--FIXED_QUALITY_CODECS = frozenset({- "ProRes HQ", "FFV1 Lossless RGB 10-bit",-})--def _normalize_codec(codec: str) -> str:- if not isinstance(codec, str):- return codec- c = codec.strip()- return _CODEC_ALIASES.get(c, c)---def _base_codec(codec: str) -> str:- norm = _normalize_codec(codec)- base = _BASE_CODEC_MAP.get(norm)- if base is None:- raise ValueError(f"Unknown video codec: {codec!r}.")- return base---def _is_nvenc_codec(codec: str) -> bool:- return _normalize_codec(codec) in _IS_NVENC_SET---def _is_hdr_allowed_codec(codec: str) -> bool:- return _normalize_codec(codec) in HDR_ALLOWED_CODECS---def hdr_mode_supported(codec: str) -> bool:- """Public helper for UI: is HDR Mode toggle meaningful for this codec?"""- return _is_hdr_allowed_codec(codec)--+CONTAINER_CHOICES = ("MP4", "MKV", "MOV")++# Backend-neutral codec choices; FFmpeg/Vulkan settings select acceleration.+CODEC_CHOICES = ("H.264", "H.265", "AV1", "ProRes Proxy", "ProRes HQ", "FFV1 Lossless RGB 10-bit")++_CODEC_ALIASES = {+ "HEVC": "H.265",+ "H265": "H.265",+ "H.265 (HEVC)": "H.265",+ "HEVC (NVIDIA NVENC)": "H.265 (NVIDIA NVENC)",+}++_BASE_CODEC_MAP = {+ "H.264": "H.264",+ "H.264 (NVIDIA NVENC)": "H.264",+ "H.265": "H.265",+ "H.265 (NVIDIA NVENC)": "H.265",+ "AV1": "AV1",+ "AV1 (NVIDIA NVENC)": "AV1",+ "ProRes Proxy": "ProRes Proxy",+ "ProRes HQ": "ProRes HQ",+ "FFV1 Lossless RGB 10-bit": "FFV1 Lossless RGB 10-bit",+}++_IS_NVENC_SET = {+ "H.264 (NVIDIA NVENC)",+ "H.265 (NVIDIA NVENC)",+ "AV1 (NVIDIA NVENC)",+}++_NVENC_ENCODERS = {+ "H.264 (NVIDIA NVENC)": "h264_nvenc",+ "H.265 (NVIDIA NVENC)": "hevc_nvenc",+ "AV1 (NVIDIA NVENC)": "av1_nvenc",+}++_DEFAULT_CONTAINERS = {+ "H.264": "MP4",+ "H.264 (NVIDIA NVENC)": "MP4",+ "H.265": "MKV",+ "H.265 (NVIDIA NVENC)": "MKV",+ "AV1": "MKV",+ "AV1 (NVIDIA NVENC)": "MKV",+ "ProRes Proxy": "MOV",+ "ProRes HQ": "MOV",+ "FFV1 Lossless RGB 10-bit": "MKV",+}++# Keep AUTO_BITRATE_DIVISORS keyed by base codec; "HEVC" alias preserved for compat.+AUTO_BITRATE_DIVISORS = {+ "H.264": 165_888,+ "H.265": 331_776,+ "HEVC": 331_776,+ "AV1": 414_720,+}++# HDR Mode is only meaningful for 10-bit capable codecs. H.264 (both CPU/NVENC) stays 8-bit SDR.+HDR_ALLOWED_CODECS = {+ "H.265",+ "H.265 (NVIDIA NVENC)",+ "AV1",+ "AV1 (NVIDIA NVENC)",+ "ProRes Proxy",+ "ProRes HQ",+ "FFV1 Lossless RGB 10-bit",+}++FIXED_QUALITY_CODECS = frozenset({+ "ProRes HQ", "FFV1 Lossless RGB 10-bit",+})++def _normalize_codec(codec: str) -> str:+ if not isinstance(codec, str):+ return codec+ c = codec.strip()+ return _CODEC_ALIASES.get(c, c).removesuffix(" (NVIDIA NVENC)")+++def _base_codec(codec: str) -> str:+ norm = _normalize_codec(codec)+ base = _BASE_CODEC_MAP.get(norm)+ if base is None:+ raise ValueError(f"Unknown video codec: {codec!r}.")+ return base+++def _is_nvenc_codec(codec: str) -> bool:+ return _normalize_codec(codec) in _IS_NVENC_SET+++def _is_hdr_allowed_codec(codec: str) -> bool:+ return _normalize_codec(codec) in HDR_ALLOWED_CODECS+++def hdr_mode_supported(codec: str) -> bool:+ """Public helper for UI: is HDR Mode toggle meaningful for this codec?"""+ return _is_hdr_allowed_codec(codec)++def container_for_codec(codec: str) -> str:- """Return the single application container selected for a video codec."""- normalized = _normalize_codec(codec)- try:- return _AUTOMATIC_CONTAINERS[normalized]- except KeyError as exc:- raise ValueError(f"Unknown video codec: {codec!r}.") from exc---def _hdr_color_args(metadata: dict | None) -> list[str]:- """Return ffmpeg color flags copying input colorspace when possible.-- We copy color_space / color_primaries / color_transfer if they are known.- For HDR mode we also ensure 10-bit; metadata may be from SDR as well – we still- copy what we have, which preserves SDR in same space if input was SDR.- """- if not metadata:- return []- args: list[str] = []- # ffprobe values map directly to ffmpeg -colorspace etc when not 'unknown'- cs = metadata.get("color_space")- if isinstance(cs, str) and cs not in ("unknown", "", None):- # ffmpeg expects 'bt709', 'bt2020nc', 'bt2020c', etc. Probe already returns that.- args.extend(["-colorspace", cs])- cp = metadata.get("color_primaries")- if isinstance(cp, str) and cp not in ("unknown", "", None):- args.extend(["-color_primaries", cp])- trc = metadata.get("color_transfer")- if isinstance(trc, str) and trc not in ("unknown", "", None):- args.extend(["-color_trc", trc])- color_range = str(metadata.get("color_range") or "").lower()- if color_range in {"pc", "jpeg", "full"}:- args.extend(["-color_range", "pc"])- elif color_range in {"tv", "mpeg", "limited"}:- args.extend(["-color_range", "tv"])- return args---def _x265_hdr_params(metadata: dict | None) -> str | None:- """Build x265-params for HDR/SDR copy when using libx265 10-bit."""- if not metadata:- return None- # x265 expects colorprim, transfer, colormatrix as specific strings- # Map ffprobe names to x265 names (they align for common cases)- mapping = {- "color_primaries": metadata.get("color_primaries", "unknown"),- "color_transfer": metadata.get("color_transfer", "unknown"),- "color_space": metadata.get("color_space", "unknown"),- }- # Filter unknowns – use bt709 fallback for SDR- prim = mapping["color_primaries"] if mapping["color_primaries"] not in ("unknown", "", None) else "bt709"- trc = mapping["color_transfer"] if mapping["color_transfer"] not in ("unknown", "", None) else "bt709"- cmat = mapping["color_space"] if mapping["color_space"] not in ("unknown", "", None) else "bt709"- # x265 colormatrix for bt2020nc is bt2020nc, for bt709 is bt709- # Ensure x265-compatible values: bt2020nc is valid, bt709 is valid- color_range = str(metadata.get("color_range") or "").lower()- range_name = "full" if color_range in {"pc", "jpeg", "full"} else "limited"- return f"colorprim={prim}:transfer={trc}:colormatrix={cmat}:range={range_name}"--+ """Return a supported default when a codec needs a new container selection."""+ normalized = _normalize_codec(codec)+ try:+ return _DEFAULT_CONTAINERS[normalized]+ except KeyError as exc:+ raise ValueError(f"Unknown video codec: {codec!r}.") from exc+++def _hdr_color_args(metadata: dict | None) -> list[str]:+ """Return ffmpeg color flags copying input colorspace when possible.++ We copy color_space / color_primaries / color_transfer if they are known.+ For HDR mode we also ensure 10-bit; metadata may be from SDR as well – we still+ copy what we have, which preserves SDR in same space if input was SDR.+ """+ if not metadata:+ return []+ args: list[str] = []+ # ffprobe values map directly to ffmpeg -colorspace etc when not 'unknown'+ cs = metadata.get("color_space")+ if isinstance(cs, str) and cs not in ("unknown", "", None):+ # ffmpeg expects 'bt709', 'bt2020nc', 'bt2020c', etc. Probe already returns that.+ args.extend(["-colorspace", "0" if cs == "gbr" else cs])+ cp = metadata.get("color_primaries")+ if isinstance(cp, str) and cp not in ("unknown", "", None):+ args.extend(["-color_primaries", cp])+ trc = metadata.get("color_transfer")+ if isinstance(trc, str) and trc not in ("unknown", "", None):+ args.extend(["-color_trc", trc])+ color_range = str(metadata.get("color_range") or "").lower()+ if color_range in {"pc", "jpeg", "full"}:+ args.extend(["-color_range", "pc"])+ elif color_range in {"tv", "mpeg", "limited"}:+ args.extend(["-color_range", "tv"])+ return args+++def _x265_hdr_params(metadata: dict | None) -> str | None:+ """Build x265-params for HDR/SDR copy when using libx265 10-bit."""+ if not metadata:+ return None+ # x265 expects colorprim, transfer, colormatrix as specific strings+ # Map ffprobe names to x265 names (they align for common cases)+ mapping = {+ "color_primaries": metadata.get("color_primaries", "unknown"),+ "color_transfer": metadata.get("color_transfer", "unknown"),+ "color_space": metadata.get("color_space", "unknown"),+ }+ # Filter unknowns – use bt709 fallback for SDR+ prim = mapping["color_primaries"] if mapping["color_primaries"] not in ("unknown", "", None) else "bt709"+ trc = mapping["color_transfer"] if mapping["color_transfer"] not in ("unknown", "", None) else "bt709"+ cmat = mapping["color_space"] if mapping["color_space"] not in ("unknown", "", None) else "bt709"+ # x265 colormatrix for bt2020nc is bt2020nc, for bt709 is bt709+ # Ensure x265-compatible values: bt2020nc is valid, bt709 is valid+ color_range = str(metadata.get("color_range") or "").lower()+ range_name = "full" if color_range in {"pc", "jpeg", "full"} else "limited"+ return f"colorprim={prim}:transfer={trc}:colormatrix={cmat}:range={range_name}"++def validate_codec_container(codec: str, container: str) -> None:+ if container not in CONTAINER_CHOICES:+ raise ValueError(f"Unknown output container: {container!r}.")norm = _normalize_codec(codec)- if norm == "ProRes Proxy" and container == "MP4":- raise ValueError("ProRes Proxy is not supported in MP4. Choose the MOV or MKV container.")- if norm in FIXED_QUALITY_CODECS and container != container_for_codec(norm):- raise ValueError(f"{norm} requires the {container_for_codec(norm)} container.")- if norm not in CODEC_CHOICES and norm not in _CODEC_ALIASES.values():- # Allow alias but error on truly unknown for early feedback; _codec_command will also validate.+ if norm in {"ProRes Proxy", "ProRes HQ"} and container == "MP4":+ raise ValueError(f"{norm} is not supported in MP4. Choose the MOV or MKV container.")+ if norm == "AV1" and container == "MOV":+ raise ValueError("AV1 is not supported in MOV. Choose the MP4 or MKV container.")+ if norm not in CODEC_CHOICES and norm not in _CODEC_ALIASES.values():+ # Allow alias but error on truly unknown for early feedback; _codec_command will also validate.if norm not in _BASE_CODEC_MAP:raise ValueError(f"Unknown video codec: {codec!r}.")-def calculate_auto_bitrate_kbps(- width: int,- height: int,- fps: float,- codec: str,- bit_depth: int = 8,-) -> int:- norm = _normalize_codec(codec)- base = _base_codec(norm) if norm in _BASE_CODEC_MAP else norm- # ProRes has no auto bitrate- if base == "ProRes Proxy" or base in FIXED_QUALITY_CODECS:- raise ValueError(f"Automatic bitrate is unavailable for codec {codec!r}.")- try:- divisor = AUTO_BITRATE_DIVISORS[base]- except KeyError:- # Fallback for HEVC alias+def containers_for_codec(codec: str) -> tuple[str, ...]:+ """Offer only containers accepted by the application's export paths."""+ container_for_codec(codec)+ choices = []+ for container in CONTAINER_CHOICES:try:- divisor = AUTO_BITRATE_DIVISORS[_normalize_codec(codec)]- except KeyError as exc:- raise ValueError(f"Automatic bitrate is unavailable for codec {codec!r}.") from exc- if width <= 0 or height <= 0 or not math.isfinite(fps) or fps <= 0 or bit_depth <= 0:- raise ValueError("Automatic bitrate requires positive dimensions, frame rate, and bit depth.")- value = width * height * fps * bit_depth * 2 / divisor- return max(1, int(math.floor(value + 0.5)))---def resolve_encoding_quality(- quality_name: str,- codec: str,- width: int,- height: int,- fps: float,- hdr_mode: bool = False,-) -> dict:- if quality_name not in ENCODING_QUALITIES:- raise ValueError(f"Unknown encoding quality: {quality_name!r}.")- norm = _normalize_codec(codec)- if norm not in CODEC_CHOICES:- # Accept HEVC alias- if norm not in _BASE_CODEC_MAP and norm != "HEVC":- raise ValueError(f"Unknown video codec: {codec!r}.")- if norm in FIXED_QUALITY_CODECS:- return {- "selection": quality_name,- "mode": "fixed-codec",- "target_bitrate_kbps": None,- "cq": None,- }- if _normalize_codec(norm) == "ProRes Proxy" or _base_codec(norm) == "ProRes Proxy":- # prores_ks otherwise ignores the application's quality selection.- # Keep profile 0 while allowing higher selections to preserve fine- # temporally stabilized detail instead of reintroducing quantizer crawl.- bits_per_mb = {- "Auto (Default)": None,- "Good": 300,- "Best": 500,- "Max": 800,- }[quality_name]- return {- "selection": quality_name,- "mode": "fixed-prores-proxy-profile",- "target_bitrate_kbps": None,- "cq": None,- "bits_per_mb": bits_per_mb,- }- if quality_name == "Max":- return {- "selection": quality_name,- "mode": "constant-quality",- "target_bitrate_kbps": None,- "cq": 0,- }- multiplier = {"Auto (Default)": 1, "Good": 2, "Best": 4}[quality_name]- bit_depth = 10 if hdr_mode and _is_hdr_allowed_codec(codec) else 8- auto = calculate_auto_bitrate_kbps(width, height, fps, codec, bit_depth=bit_depth)- return {- "selection": quality_name,- "mode": "target-bitrate",- "auto_bitrate_kbps": auto,- "multiplier": multiplier,- "target_bitrate_kbps": auto * multiplier,- "cq": None,- }+ validate_codec_container(codec, container)+ except ValueError:+ continue+ choices.append(container)+ return tuple(choices)+++def resolve_container(codec: str, container: str) -> str:+ """Validate and honor the user's selected export container."""+ validate_codec_container(codec, container)+ return container+++def calculate_auto_bitrate_kbps(+ width: int,+ height: int,+ fps: float,+ codec: str,+ bit_depth: int = 8,+) -> int:+ norm = _normalize_codec(codec)+ base = _base_codec(norm) if norm in _BASE_CODEC_MAP else norm+ # ProRes has no auto bitrate+ if base == "ProRes Proxy" or base in FIXED_QUALITY_CODECS:+ raise ValueError(f"Automatic bitrate is unavailable for codec {codec!r}.")+ try:+ divisor = AUTO_BITRATE_DIVISORS[base]+ except KeyError:+ # Fallback for HEVC alias+ try:+ divisor = AUTO_BITRATE_DIVISORS[_normalize_codec(codec)]+ except KeyError as exc:+ raise ValueError(f"Automatic bitrate is unavailable for codec {codec!r}.") from exc+ if width <= 0 or height <= 0 or not math.isfinite(fps) or fps <= 0 or bit_depth <= 0:+ raise ValueError("Automatic bitrate requires positive dimensions, frame rate, and bit depth.")+ value = width * height * fps * bit_depth * 2 / divisor+ return max(1, int(math.floor(value + 0.5)))+++def resolve_encoding_quality(+ quality_name: str,+ codec: str,+ width: int,+ height: int,+ fps: float,+ hdr_mode: bool = False,+) -> dict:+ if quality_name not in ENCODING_QUALITIES:+ raise ValueError(f"Unknown encoding quality: {quality_name!r}.")+ norm = _normalize_codec(codec)+ if norm not in CODEC_CHOICES:+ # Accept HEVC alias+ if norm not in _BASE_CODEC_MAP and norm != "HEVC":+ raise ValueError(f"Unknown video codec: {codec!r}.")+ if norm in FIXED_QUALITY_CODECS:+ return {+ "selection": quality_name,+ "mode": "fixed-codec",+ "target_bitrate_kbps": None,+ "cq": None,+ }+ if _normalize_codec(norm) == "ProRes Proxy" or _base_codec(norm) == "ProRes Proxy":+ # prores_ks otherwise ignores the application's quality selection.+ # Keep profile 0 while allowing higher selections to preserve fine+ # temporally stabilized detail instead of reintroducing quantizer crawl.+ bits_per_mb = {+ "Auto (Default)": None,+ "Good": 300,+ "Best": 500,+ "Max": 800,+ }[quality_name]+ return {+ "selection": quality_name,+ "mode": "fixed-prores-proxy-profile",+ "target_bitrate_kbps": None,+ "cq": None,+ "bits_per_mb": bits_per_mb,+ }+ if quality_name == "Max":+ return {+ "selection": quality_name,+ "mode": "constant-quality",+ "target_bitrate_kbps": None,+ "cq": 0,+ }+ multiplier = {"Auto (Default)": 1, "Good": 2, "Best": 4}[quality_name]+ bit_depth = 10 if hdr_mode and _is_hdr_allowed_codec(codec) else 8+ auto = calculate_auto_bitrate_kbps(width, height, fps, codec, bit_depth=bit_depth)+ return {+ "selection": quality_name,+ "mode": "target-bitrate",+ "auto_bitrate_kbps": auto,+ "multiplier": multiplier,+ "target_bitrate_kbps": auto * multiplier,+ "cq": None,+ }diff --git a/src/core/ffmpeg/encoder.py b/src/core/ffmpeg/encoder.pyindex 4c049de..2c09474 100644--- a/src/core/ffmpeg/encoder.py+++ b/src/core/ffmpeg/encoder.py@@ -1,463 +1,379 @@-from __future__ import annotations--import subprocess-import threading-from functools import lru_cache-from pathlib import Path--from ..jobs import BoundedLogBuffer, JobController, drain_bounded_text, drain_text-from ..paths import FFMPEG-from .audio import AudioPlan, plan_audio_streams-from .codecs import (- CODEC_CHOICES, _NVENC_ENCODERS, _base_codec, _hdr_color_args,- _is_hdr_allowed_codec, _is_nvenc_codec, _normalize_codec, _x265_hdr_params,- resolve_encoding_quality,-)--@lru_cache(maxsize=128)-def _encoder_probe(- codec: str, width: int, height: int, gpu_ordinal: int | None = None-) -> bool:- gpu_args = ["-gpu", str(gpu_ordinal)] if gpu_ordinal is not None else []- command = [- str(FFMPEG),- "-v",- "error",- "-f",- "lavfi",- "-i",- f"color=size={width}x{height}:rate=1",- "-frames:v",- "1",- "-c:v",- codec,- *gpu_args,- "-f",- "null",- "-",- ]- return (- subprocess.run(- command,- stdout=subprocess.DEVNULL,- stderr=subprocess.DEVNULL,- creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),- ).returncode- == 0- )---@lru_cache(maxsize=16)-def _cpu_encoder_available(codec: str) -> bool:- """Probe CPU encoder initialization once at a tiny resolution."""- return _encoder_probe(codec, 64, 64, None)---# Legacy mapping kept for external callers; new display names use _NVENC_ENCODERS.-_NVENC_CODECS = {- "H.264": "h264_nvenc",- "HEVC": "hevc_nvenc",- "AV1": "av1_nvenc",- "H.265": "hevc_nvenc",- "H.264 (NVIDIA NVENC)": "h264_nvenc",- "H.265 (NVIDIA NVENC)": "hevc_nvenc",- "AV1 (NVIDIA NVENC)": "av1_nvenc",-}---def probe_nvenc_codecs(gpu_ordinal: int) -> tuple[str, ...]:- """Return user-facing codecs that can initialize NVENC on one CUDA device.-- Returns display names like "H.264 (NVIDIA NVENC)" so UI can filter.- """- # Probe the three actual NVENC encoders once, then map to display names.- mapping = {- "h264_nvenc": "H.264 (NVIDIA NVENC)",- "hevc_nvenc": "H.265 (NVIDIA NVENC)",- "av1_nvenc": "AV1 (NVIDIA NVENC)",- }- supported = []- for encoder, display in mapping.items():- if _encoder_probe(encoder, 256, 256, int(gpu_ordinal)):- supported.append(display)- return tuple(supported)---def resolve_video_gpu(- gpus: tuple[dict, ...],- gpu_uuid: str,- codec: str,- width: int,- height: int,-) -> dict | None:- """Resolve a stable UUID to a device that supports the requested NVENC codec.-- CPU codecs (plain H.264/H.265/AV1 without '(NVIDIA NVENC)') never require a GPU.- NVENC codecs explicitly require a cuda device that can init the encoder.- """- norm = _normalize_codec(codec)- if norm == "ProRes Proxy":- return None- # CPU variants do not need a GPU- if not _is_nvenc_codec(norm):- # Validate that plain codecs are known; if unknown, raise.- if norm not in CODEC_CHOICES and norm not in ("HEVC", "H.265"):- # Try base check- try:- _base_codec(norm)- except ValueError as exc:- raise ValueError(f"Unknown video codec: {codec!r}.") from exc- # Plain variants: no GPU needed (CPU encoding)- return None- # NVENC path- try:- encoder = _NVENC_ENCODERS[norm]- except KeyError as exc:- raise ValueError(f"Unknown video codec: {codec!r}.") from exc- candidates = [gpu for gpu in gpus if gpu.get("cuda_ordinal") is not None]- if gpu_uuid != "auto":- candidates = [gpu for gpu in candidates if gpu.get("uuid") == gpu_uuid]- if not candidates:- raise RuntimeError("The selected Video Processing GPU is unavailable.")- for gpu in candidates:- ordinal = int(gpu["cuda_ordinal"])- if _encoder_probe(encoder, width, height, ordinal):- selected = dict(gpu)- selected["nvenc_codec"] = encoder- return selected- selection = "selected GPU" if gpu_uuid != "auto" else "available NVIDIA GPUs"- raise RuntimeError(- f"{norm} cannot encode the requested {width}×{height} output on the "- f"{selection}. Choose another Video Processing GPU, codec, or output size."- )---def _codec_command(- codec: str,- quality_name: str,- width: int,- height: int,- fps: float,- gpu_ordinal: int | None = None,- require_nvenc: bool = False,- hdr_mode: bool = False,- hdr_metadata: dict | None = None,- *,- speed_profile: str = "default", output_depth: int | None = None,-) -> tuple[list[str], str, dict]:- """Return FFmpeg codec args for an explicit user-facing codec choice.-- Plain names (H.264, H.265, AV1) are strictly CPU (libx264/libx265/libsvtav1).- Suffixed names (H.264 (NVIDIA NVENC) etc.) are strictly NVENC and require a GPU.- `require_nvenc` is kept for backward compat – NVENC codecs always require NVENC,- CPU codecs always forbid fallback to NVENC.- When ``hdr_mode`` is True, output is 10-bit (yuv420p10le/p010le) and input- colorspace is copied via ``hdr_metadata`` for HDR_ALLOWED_CODECS.- """- if speed_profile not in {"default", "neural", "preview"}:- raise ValueError(f"Unknown encoder speed profile: {speed_profile!r}.")- software_preset = {"default": "slow", "neural": "medium", "preview": "veryfast"}[speed_profile]-- norm = _normalize_codec(codec)- if hdr_mode and not _is_hdr_allowed_codec(norm):- raise ValueError(- f"HDR Mode is not available for {codec!r}; choose H.265, H.265 (NVIDIA NVENC), "- "AV1, AV1 (NVIDIA NVENC), ProRes, or FFV1 Lossless RGB 10-bit."- )- high_depth = hdr_mode or (output_depth is not None and output_depth > 8)- quality = resolve_encoding_quality(quality_name, codec, width, height, fps, hdr_mode=high_depth)- # ProRes Proxy is always 10-bit; HDR just copies colorspace- if norm == "ProRes Proxy":- hdr_extra = _hdr_color_args(hdr_metadata) if hdr_metadata else []- prores_quality = (- ["-bits_per_mb", str(int(quality["bits_per_mb"]))]- if quality.get("bits_per_mb") is not None- else []- )- return (- [- "-c:v", "prores_ks", "-profile:v", "0",- *prores_quality, "-pix_fmt", "yuv422p10le", *hdr_extra,- ],- "prores_ks (Proxy)",- quality,- )- if norm == "ProRes HQ":- return (- ["-c:v", "prores_ks", "-profile:v", "3", "-pix_fmt", "yuv422p10le",- *(_hdr_color_args(hdr_metadata) if hdr_metadata else [])],- "prores_ks (HQ)", quality,- )- if norm == "FFV1 Lossless RGB 10-bit":- return (- ["-c:v", "ffv1", "-level", "3", "-slicecrc", "1", "-pix_fmt", "gbrp10le",- "-color_range", "pc"],- "ffv1 (Lossless RGB 10-bit)", quality,- )- if quality["mode"] == "constant-quality":- nvenc_quality = ["-rc", "vbr", "-cq", "0", "-b:v", "0"]- software_quality = ["-crf", "0"]- bitrate = None- else:- bitrate = f"{quality['target_bitrate_kbps']}k"- nvenc_quality = ["-rc", "vbr", "-b:v", bitrate]- software_quality = ["-b:v", bitrate]- gpu_args = ["-gpu", str(gpu_ordinal)] if gpu_ordinal is not None else []- signal_metadata = hdr_metadata- if high_depth and not hdr_mode:- signal_metadata = dict(hdr_metadata or {})- for field in ("color_space", "color_primaries", "color_transfer"):- if signal_metadata.get(field) in (None, "", "unknown", "unspecified"):- signal_metadata[field] = "bt709"- hdr_color = _hdr_color_args(signal_metadata) if signal_metadata else []-- # CPU variants – never probe NVENC, always use software encoder- if norm == "H.264":- # H.264 is always 8-bit SDR – HDR Mode is not allowed (checked above), so plain yuv420p- if require_nvenc:- raise RuntimeError(- f"H.264 (CPU) was requested but NVENC was required; choose H.264 (NVIDIA NVENC) for GPU encoding."- )- if hdr_mode:- raise ValueError("HDR Mode is not available for H.264; choose H.265/AV1/ProRes.")- x264_color = _x265_hdr_params(signal_metadata)- return (- ["-c:v", "libx264", "-preset", software_preset, *software_quality,- "-pix_fmt", "yuv420p",- *(["-x264-params", x264_color] if x264_color else []), *hdr_color],- "libx264",- quality,- )- if norm == "H.265" or norm == "HEVC":- if require_nvenc:- raise RuntimeError(- f"H.265 (CPU) was requested but NVENC was required; choose H.265 (NVIDIA NVENC) for GPU encoding."- )- # Source precision or HDR selects 10-bit independently of SDR transfer.- pix_fmt = "yuv420p10le" if high_depth else "yuv420p"- if high_depth:- x265_params = _x265_hdr_params(signal_metadata)- x265_extra = ["-x265-params", x265_params] if x265_params else []- range_extra = (- ["-color_range", "pc"]- if str((signal_metadata or {}).get("color_range") or "").lower()- in {"pc", "jpeg", "full"} else []- )- # x265 owns VUI color fields; the generic range flag also tags the stream.- return (- ["-c:v", "libx265", "-preset", software_preset, *software_quality, "-pix_fmt", pix_fmt, *x265_extra, *range_extra],- "libx265",- quality,- )- return (- ["-c:v", "libx265", "-preset", software_preset, *software_quality, "-pix_fmt", pix_fmt, *hdr_color],- "libx265",- quality,- )+from __future__ import annotations++import subprocess+import threading+from functools import lru_cache+from pathlib import Path++from ..jobs import BoundedLogBuffer, JobController, drain_bounded_text, drain_text+from ..paths import FFMPEG+from .audio import AudioPlan, plan_audio_streams+from .codecs import (+ CODEC_CHOICES, _NVENC_ENCODERS, _base_codec, _hdr_color_args,+ _is_hdr_allowed_codec, _is_nvenc_codec, _normalize_codec, _x265_hdr_params,+ resolve_encoding_quality,+)++@lru_cache(maxsize=128)+def _encoder_probe(+ codec: str, width: int, height: int, gpu_ordinal: int | None = None+) -> bool:+ gpu_args = ["-gpu", str(gpu_ordinal)] if gpu_ordinal is not None else []+ command = [+ str(FFMPEG),+ "-v",+ "error",+ "-f",+ "lavfi",+ "-i",+ f"color=size={width}x{height}:rate=1",+ "-frames:v",+ "1",+ "-c:v",+ codec,+ *gpu_args,+ "-f",+ "null",+ "-",+ ]+ return (+ subprocess.run(+ command,+ stdout=subprocess.DEVNULL,+ stderr=subprocess.DEVNULL,+ creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),+ ).returncode+ == 0+ )+++@lru_cache(maxsize=16)+def _cpu_encoder_available(codec: str) -> bool:+ """Probe CPU encoder initialization once at a tiny resolution."""+ return _encoder_probe(codec, 64, 64, None)+++# Legacy mapping kept for external callers; new display names use _NVENC_ENCODERS.+_NVENC_CODECS = {+ "H.264": "h264_nvenc",+ "HEVC": "hevc_nvenc",+ "AV1": "av1_nvenc",+ "H.265": "hevc_nvenc",+ "H.264 (NVIDIA NVENC)": "h264_nvenc",+ "H.265 (NVIDIA NVENC)": "hevc_nvenc",+ "AV1 (NVIDIA NVENC)": "av1_nvenc",+}+++def probe_nvenc_codecs(gpu_ordinal: int) -> tuple[str, ...]:+ """Return user-facing codecs that can initialize NVENC on one CUDA device.++ Returns display names like "H.264 (NVIDIA NVENC)" so UI can filter.+ """+ # Probe the three actual NVENC encoders once, then map to display names.+ mapping = {+ "h264_nvenc": "H.264 (NVIDIA NVENC)",+ "hevc_nvenc": "H.265 (NVIDIA NVENC)",+ "av1_nvenc": "AV1 (NVIDIA NVENC)",+ }+ supported = []+ for encoder, display in mapping.items():+ if _encoder_probe(encoder, 256, 256, int(gpu_ordinal)):+ supported.append(display)+ return tuple(supported)+++def resolve_video_gpu(+ gpus: tuple[dict, ...],+ gpu_uuid: str,+ codec: str,+ width: int,+ height: int,+) -> dict | None:+ """Legacy NVIDIA selector; FFmpeg/Vulkan now owns codec assignment."""+ _base_codec(codec)+ return None+++def _codec_command(+ codec: str,+ quality_name: str,+ width: int,+ height: int,+ fps: float,+ gpu_ordinal: int | None = None,+ require_nvenc: bool = False,+ hdr_mode: bool = False,+ hdr_metadata: dict | None = None,+ *,+ speed_profile: str = "default", output_depth: int | None = None,+) -> tuple[list[str], str, dict]:+ """Return software fallback args; command planning selects Vulkan codecs.++ HDR/source depth is retained independently of the codec backend.+ """+ if speed_profile not in {"default", "neural", "preview"}:+ raise ValueError(f"Unknown encoder speed profile: {speed_profile!r}.")+ software_preset = {"default": "slow", "neural": "medium", "preview": "veryfast"}[speed_profile]++ norm = _normalize_codec(codec)+ if hdr_mode and not _is_hdr_allowed_codec(norm):+ raise ValueError(+ f"HDR Mode is not available for {codec!r}; choose H.265, H.265 (NVIDIA NVENC), "+ "AV1, AV1 (NVIDIA NVENC), ProRes, or FFV1 Lossless RGB 10-bit."+ )+ high_depth = hdr_mode or (output_depth is not None and output_depth > 8)+ quality = resolve_encoding_quality(quality_name, codec, width, height, fps, hdr_mode=high_depth)+ # ProRes Proxy is always 10-bit; HDR just copies colorspace+ if norm == "ProRes Proxy":+ hdr_extra = _hdr_color_args(hdr_metadata) if hdr_metadata else []+ prores_quality = (+ ["-bits_per_mb", str(int(quality["bits_per_mb"]))]+ if quality.get("bits_per_mb") is not None+ else []+ )+ return (+ [+ "-c:v", "prores_ks", "-profile:v", "0",+ *prores_quality, "-pix_fmt", "yuv422p10le", *hdr_extra,+ ],+ "prores_ks (Proxy)",+ quality,+ )+ if norm == "ProRes HQ":+ return (+ ["-c:v", "prores_ks", "-profile:v", "3", "-pix_fmt", "yuv422p10le",+ *(_hdr_color_args(hdr_metadata) if hdr_metadata else [])],+ "prores_ks (HQ)", quality,+ )+ if norm == "FFV1 Lossless RGB 10-bit":+ return (+ ["-c:v", "ffv1", "-level", "3", "-slicecrc", "1", "-pix_fmt", "gbrp10le",+ "-color_range", "pc"],+ "ffv1 (Lossless RGB 10-bit)", quality,+ )+ if quality["mode"] == "constant-quality":+ nvenc_quality = ["-rc", "vbr", "-cq", "0", "-b:v", "0"]+ software_quality = ["-crf", "0"]+ bitrate = None+ else:+ bitrate = f"{quality['target_bitrate_kbps']}k"+ nvenc_quality = ["-rc", "vbr", "-b:v", bitrate]+ software_quality = ["-b:v", bitrate]+ gpu_args = ["-gpu", str(gpu_ordinal)] if gpu_ordinal is not None else []+ signal_metadata = hdr_metadata+ if high_depth and not hdr_mode:+ signal_metadata = dict(hdr_metadata or {})+ for field in ("color_space", "color_primaries", "color_transfer"):+ if signal_metadata.get(field) in (None, "", "unknown", "unspecified"):+ signal_metadata[field] = "bt709"+ hdr_color = _hdr_color_args(signal_metadata) if signal_metadata else []++ # CPU variants – never probe NVENC, always use software encoder+ if norm == "H.264":+ # H.264 is always 8-bit SDR – HDR Mode is not allowed (checked above), so plain yuv420p+ if hdr_mode:+ raise ValueError("HDR Mode is not available for H.264; choose H.265/AV1/ProRes.")+ x264_color = _x265_hdr_params(signal_metadata)+ return (+ ["-c:v", "libx264", "-preset", software_preset, *software_quality,+ "-pix_fmt", "yuv420p",+ *(["-x264-params", x264_color] if x264_color else []), *hdr_color],+ "libx264",+ quality,+ )+ if norm == "H.265" or norm == "HEVC":+ # Source precision or HDR selects 10-bit independently of SDR transfer.+ pix_fmt = "yuv420p10le" if high_depth else "yuv420p"+ if high_depth:+ x265_params = _x265_hdr_params(signal_metadata)+ x265_extra = ["-x265-params", x265_params] if x265_params else []+ range_extra = (+ ["-color_range", "pc"]+ if str((signal_metadata or {}).get("color_range") or "").lower()+ in {"pc", "jpeg", "full"} else []+ )+ # x265 owns VUI color fields; the generic range flag also tags the stream.+ return (+ ["-c:v", "libx265", "-preset", software_preset, *software_quality, "-pix_fmt", pix_fmt, *x265_extra, *range_extra],+ "libx265",+ quality,+ )+ return (+ ["-c:v", "libx265", "-preset", software_preset, *software_quality, "-pix_fmt", pix_fmt, *hdr_color],+ "libx265",+ quality,+ )if norm == "AV1":- if require_nvenc:- raise RuntimeError(- "AV1 (CPU) was requested but NVENC was required; choose AV1 (NVIDIA NVENC) for GPU encoding."- )- pix_fmt = "yuv420p10le" if high_depth else "yuv420p"- # Prefer libsvtav1 (fastest CPU AV1), fallback to libaom-av1- if _cpu_encoder_available("libsvtav1"):- if quality["mode"] == "constant-quality":- return (- ["-c:v", "libsvtav1", "-preset", "6", "-crf", "0", "-pix_fmt", pix_fmt, *hdr_color],- "libsvtav1",- quality,- )- return (- ["-c:v", "libsvtav1", "-preset", "6", "-b:v", bitrate, "-pix_fmt", pix_fmt, *hdr_color],- "libsvtav1",- quality,- )- if _cpu_encoder_available("libaom-av1"):- if quality["mode"] == "constant-quality":- return (- ["-c:v", "libaom-av1", "-cpu-used", "4", "-crf", "0", "-b:v", "0", "-pix_fmt", pix_fmt, *hdr_color],- "libaom-av1",- quality,- )- return (- ["-c:v", "libaom-av1", "-cpu-used", "6", "-b:v", bitrate, "-pix_fmt", pix_fmt, *hdr_color],- "libaom-av1",- quality,- )- raise RuntimeError(- "AV1 CPU encoding is unavailable: neither libsvtav1 nor libaom-av1 can initialize. "- "Choose H.264/H.265 or AV1 (NVIDIA NVENC) if a GPU is available."- )-- # NVENC variants – strictly require NVENC probe success- if norm == "H.264 (NVIDIA NVENC)":- if hdr_mode:- raise ValueError("HDR Mode is not available for H.264 (NVIDIA NVENC); choose H.265/AV1.")- if not _encoder_probe("h264_nvenc", width, height, gpu_ordinal):- raise RuntimeError(- f"H.264 (NVIDIA NVENC) cannot encode {width}×{height} on the selected Video Processing GPU. "- "Choose H.264 (CPU) or another GPU."- )- return (- [- "-c:v", "h264_nvenc", *gpu_args, "-preset", "p6", "-tune", "hq",- *nvenc_quality, "-pix_fmt", "yuv420p",- ],- "h264_nvenc",- quality,- )- if norm == "H.265 (NVIDIA NVENC)":- if not _encoder_probe("hevc_nvenc", width, height, gpu_ordinal):- raise RuntimeError(- f"H.265 (NVIDIA NVENC) cannot encode {width}×{height} on the selected Video Processing GPU. "- "Choose H.265 (CPU) or another GPU."- )- pix_fmt = "p010le" if high_depth else "yuv420p"- # HEVC HDR should use main10 implicitly via p010le- return (- [- "-c:v", "hevc_nvenc", *gpu_args, "-preset", "p6", "-tune", "hq",- *nvenc_quality, "-pix_fmt", pix_fmt, *hdr_color,- ],- "hevc_nvenc",- quality,- )- if norm == "AV1 (NVIDIA NVENC)":- if not _encoder_probe("av1_nvenc", width, height, gpu_ordinal):- raise RuntimeError(- f"AV1 (NVIDIA NVENC) cannot encode {width}×{height} on the selected GPU/driver. "- "Choose AV1 (CPU) with libsvtav1, or H.264/H.265, or a lower upscaling factor."- )- pix_fmt = "p010le" if high_depth else "yuv420p"- return (- ["-c:v", "av1_nvenc", *gpu_args, "-preset", "p6", *nvenc_quality, "-pix_fmt", pix_fmt, *hdr_color],- "av1_nvenc",- quality,- )-- raise ValueError(f"Unknown video codec: {codec!r}.")---def start_encoder(- temp_video: Path,- codec: str,- quality_name: str,- controller: JobController,- width: int,- height: int,- fps: float,- gpu_ordinal: int | None = None,- require_nvenc: bool = False,- hdr_mode: bool = False,- hdr_metadata: dict | None = None,- preserve_timestamps: bool = False,- *, video_filter: str | None = None, keep_start_time: bool = False, bounded_logs: bool = False,- speed_profile: str = "default", source_audio: Path | None = None,- direct_container: str | None = None, comment: str | None = None,- audio_duration: float | None = None, include_source_metadata: bool = True,- audio_plan: AudioPlan | None = None, output_depth: int | None = None,-):- codec_args, selected, quality = _codec_command(- codec, quality_name, width, height, fps, gpu_ordinal, require_nvenc, hdr_mode, hdr_metadata,- speed_profile=speed_profile, output_depth=output_depth,- )- normalized_codec = _normalize_codec(codec)- if (output_depth is not None and output_depth > 8- and str((hdr_metadata or {}).get("color_range") or "").lower()- in {"pc", "jpeg", "full"}- and normalized_codec in {"H.265", "HEVC", "AV1"}):- range_filter = "scale=in_range=pc:out_range=pc"- video_filter = f"{video_filter},{range_filter}" if video_filter else range_filter- if normalized_codec in {"ProRes Proxy", "ProRes HQ", "FFV1 Lossless RGB 10-bit"}:- colors = hdr_metadata or {}- primaries = str(colors.get("color_primaries") or "bt709")- transfer = str(colors.get("color_transfer") or "bt709")- if primaries in {"unknown", "unspecified"}:- primaries = "bt2020" if colors.get("hdr") else "bt709"- if transfer in {"unknown", "unspecified"}:- transfer = "smpte2084" if colors.get("hdr") else "bt709"- if normalized_codec == "FFV1 Lossless RGB 10-bit":- tag_filter = ("format=gbrp10le,setparams="- f"color_primaries={primaries}:color_trc={transfer}:"- "colorspace=gbr:range=full")- else:- matrix = str(colors.get("color_space") or "bt709")- if matrix in {"unknown", "unspecified"}:- matrix = "bt2020nc" if colors.get("hdr") else "bt709"- tag_filter = ("format=yuv422p10le,setparams="- f"color_primaries={primaries}:color_trc={transfer}:"- f"colorspace={matrix}:range=limited")+ pix_fmt = "yuv420p10le" if high_depth else "yuv420p"+ # Prefer libsvtav1 (fastest CPU AV1), fallback to libaom-av1+ if _cpu_encoder_available("libsvtav1"):+ if quality["mode"] == "constant-quality":+ return (+ ["-c:v", "libsvtav1", "-preset", "6", "-crf", "0", "-pix_fmt", pix_fmt, *hdr_color],+ "libsvtav1",+ quality,+ )+ return (+ ["-c:v", "libsvtav1", "-preset", "6", "-b:v", bitrate, "-pix_fmt", pix_fmt, *hdr_color],+ "libsvtav1",+ quality,+ )+ if _cpu_encoder_available("libaom-av1"):+ if quality["mode"] == "constant-quality":+ return (+ ["-c:v", "libaom-av1", "-cpu-used", "4", "-crf", "0", "-b:v", "0", "-pix_fmt", pix_fmt, *hdr_color],+ "libaom-av1",+ quality,+ )+ return (+ ["-c:v", "libaom-av1", "-cpu-used", "6", "-b:v", bitrate, "-pix_fmt", pix_fmt, *hdr_color],+ "libaom-av1",+ quality,+ )+ raise RuntimeError(+ "AV1 CPU encoding is unavailable: neither libsvtav1 nor libaom-av1 can initialize. "+ "Choose H.264 or H.265."+ )++ raise ValueError(f"Unknown video codec: {codec!r}.")+++def start_encoder(+ temp_video: Path,+ codec: str,+ quality_name: str,+ controller: JobController,+ width: int,+ height: int,+ fps: float,+ gpu_ordinal: int | None = None,+ require_nvenc: bool = False,+ hdr_mode: bool = False,+ hdr_metadata: dict | None = None,+ preserve_timestamps: bool = False,+ *, video_filter: str | None = None, keep_start_time: bool = False, bounded_logs: bool = False,+ speed_profile: str = "default", source_audio: Path | None = None,+ direct_container: str | None = None, comment: str | None = None,+ audio_duration: float | None = None, include_source_metadata: bool = True,+ audio_plan: AudioPlan | None = None, output_depth: int | None = None,+):+ codec_args, selected, quality = _codec_command(+ codec, quality_name, width, height, fps, gpu_ordinal, require_nvenc, hdr_mode, hdr_metadata,+ speed_profile=speed_profile, output_depth=output_depth,+ )+ normalized_codec = _normalize_codec(codec)+ if (output_depth is not None and output_depth > 8+ and str((hdr_metadata or {}).get("color_range") or "").lower()+ in {"pc", "jpeg", "full"}+ and normalized_codec in {"H.265", "HEVC", "AV1"}):+ range_filter = "scale=in_range=pc:out_range=pc"+ video_filter = f"{video_filter},{range_filter}" if video_filter else range_filter+ if normalized_codec in {"ProRes Proxy", "ProRes HQ", "FFV1 Lossless RGB 10-bit"}:+ colors = hdr_metadata or {}+ primaries = str(colors.get("color_primaries") or "bt709")+ transfer = str(colors.get("color_transfer") or "bt709")+ if primaries in {"unknown", "unspecified"}:+ primaries = "bt2020" if colors.get("hdr") else "bt709"+ if transfer in {"unknown", "unspecified"}:+ transfer = "smpte2084" if colors.get("hdr") else "bt709"+ if normalized_codec == "FFV1 Lossless RGB 10-bit":+ tag_filter = ("format=gbrp10le,setparams="+ f"color_primaries={primaries}:color_trc={transfer}:"+ "colorspace=gbr:range=full")+ else:+ matrix = str(colors.get("color_space") or "bt709")+ if matrix in {"unknown", "unspecified"}:+ matrix = "bt2020nc" if colors.get("hdr") else "bt709"+ tag_filter = ("format=yuv422p10le,setparams="+ f"color_primaries={primaries}:color_trc={transfer}:"+ f"colorspace={matrix}:range=limited")video_filter = f"{video_filter},{tag_filter}" if video_filter else tag_filter- direct_mux = source_audio is not None and direct_container in {"MP4", "MOV"}- if direct_mux:- selected_audio = audio_plan or plan_audio_streams(source_audio, direct_container, controller)- command = [- str(FFMPEG),- "-hide_banner",- "-loglevel",- "warning",- "-y",- *( ["-copyts"] if keep_start_time else [] ),- "-f",- "nut",- "-i",- "pipe:0",- *( ["-t", f"{float(audio_duration):.9f}"] if audio_duration is not None and audio_duration > 0 else [] ),- "-i",- str(source_audio),- "-map",- "0:v:0",- "-map",- "1:a?",- *( ["-map_metadata", "1", "-map_chapters", "1"] if include_source_metadata else ["-map_metadata", "-1", "-map_chapters", "-1"] ),- *( ["-vf", video_filter] if video_filter else [] ),- *codec_args,- *selected_audio.encoder_args(),- "-fps_mode",- "passthrough",- *( ["-enc_time_base:v", "demux"] if preserve_timestamps else [] ),- "-movflags",- "+faststart",- "-metadata:s:v:0",- "rotate=0",- *( ["-metadata", "comment=" + comment] if comment is not None else [] ),- *( ["-avoid_negative_ts", "disabled"] if keep_start_time else [] ),- str(temp_video),- ]- else:- command = [- str(FFMPEG),- "-hide_banner",- "-loglevel",- "warning",- "-y",- *( ["-copyts"] if keep_start_time else [] ),- "-f",- "nut",- "-i",- "pipe:0",- "-map",- "0:v:0",- "-an",- *( ["-vf", video_filter] if video_filter else [] ),- *codec_args,- "-fps_mode",- "passthrough",- *( ["-enc_time_base:v", "demux"] if preserve_timestamps else [] ),- *( ["-avoid_negative_ts", "disabled"] if keep_start_time else [] ),- str(temp_video),- ]- process = subprocess.Popen(- command,- stdin=subprocess.PIPE,- stdout=subprocess.DEVNULL,- stderr=subprocess.PIPE,- creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),- )- controller.register(process)- logs = BoundedLogBuffer(max_tail=60) if bounded_logs else []- assert process.stderr is not None- thread = threading.Thread(target=drain_bounded_text if bounded_logs else drain_text, args=(process.stderr, logs), daemon=True)- thread.start()- return process, thread, logs, selected, quality+ # Raw NUT RGB frames do not reliably carry transfer/primaries tags between+ # the bundled FFmpeg and PyAV versions. Describe their actual signal before+ # Vulkan format conversion so PQ is preserved instead of reinterpreted as SDR.+ colors = hdr_metadata or {}+ primaries = str(colors.get("color_primaries") or ("bt2020" if hdr_mode else "bt709"))+ transfer = str(colors.get("color_transfer") or ("smpte2084" if hdr_mode else "bt709"))+ if primaries in {"unknown", "unspecified"}:+ primaries = "bt2020" if hdr_mode else "bt709"+ if transfer in {"unknown", "unspecified"}:+ transfer = "smpte2084" if hdr_mode else "bt709"+ input_tags = f"setparams=colorspace=gbr:range=full:color_primaries={primaries}:color_trc={transfer}"+ video_filter = input_tags + ("," + video_filter if video_filter else "")+ direct_mux = source_audio is not None and direct_container in {"MP4", "MOV"}+ if direct_mux:+ selected_audio = audio_plan or plan_audio_streams(source_audio, direct_container, controller)+ command = [+ str(FFMPEG),+ "-hide_banner",+ "-loglevel",+ "warning",+ "-y",+ *( ["-copyts"] if keep_start_time else [] ),+ "-f",+ "nut",+ "-i",+ "pipe:0",+ *( ["-t", f"{float(audio_duration):.9f}"] if audio_duration is not None and audio_duration > 0 else [] ),+ "-i",+ str(source_audio),+ "-map",+ "0:v:0",+ "-map",+ "1:a?",+ *( ["-map_metadata", "1", "-map_chapters", "1"] if include_source_metadata else ["-map_metadata", "-1", "-map_chapters", "-1"] ),+ *( ["-vf", video_filter] if video_filter else [] ),+ *codec_args,+ *selected_audio.encoder_args(),+ "-fps_mode",+ "passthrough",+ *( ["-enc_time_base:v", "demux"] if preserve_timestamps else [] ),+ "-movflags",+ "+faststart",+ "-metadata:s:v:0",+ "rotate=0",+ *( ["-metadata", "comment=" + comment] if comment is not None else [] ),+ *( ["-avoid_negative_ts", "disabled"] if keep_start_time else [] ),+ str(temp_video),+ ]+ else:+ command = [+ str(FFMPEG),+ "-hide_banner",+ "-loglevel",+ "warning",+ "-y",+ *( ["-copyts"] if keep_start_time else [] ),+ "-f",+ "nut",+ "-i",+ "pipe:0",+ "-map",+ "0:v:0",+ "-an",+ *( ["-vf", video_filter] if video_filter else [] ),+ *codec_args,+ "-fps_mode",+ "passthrough",+ *( ["-enc_time_base:v", "demux"] if preserve_timestamps else [] ),+ *( ["-avoid_negative_ts", "disabled"] if keep_start_time else [] ),+ str(temp_video),+ ]+ from .vulkan import prepare_command+ command = prepare_command(command, selection=getattr(controller, "ffmpeg_device", None), dimensions=(width, height),+ rate=str(fps), time_base=str((hdr_metadata or {}).get("time_base") or "1/90000") if preserve_timestamps else None)+ selected = command[command.index("-c:v") + 1]+ process = subprocess.Popen(+ command,+ stdin=subprocess.PIPE,+ stdout=subprocess.DEVNULL,+ stderr=subprocess.PIPE,+ creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),+ )+ controller.register(process)+ logs = BoundedLogBuffer(max_tail=60) if bounded_logs else []+ assert process.stderr is not None+ thread = threading.Thread(target=drain_bounded_text if bounded_logs else drain_text, args=(process.stderr, logs), daemon=True)+ thread.start()+ return process, thread, logs, selected, qualitydiff --git a/src/core/ffmpeg/filters.py b/src/core/ffmpeg/filters.pynew file mode 100644index 0000000..3a7708f--- /dev/null+++ b/src/core/ffmpeg/filters.py@@ -0,0 +1,142 @@+"""GPU pixel operations shared by file and host-frame media pipelines."""+from __future__ import annotations++import hashlib+import subprocess+import tempfile+from pathlib import Path++import numpy as np++from ..jobs import Cancelled, JobController+from ..paths import FFMPEG, APP_TEMP+from .vulkan import device_args, filter_device, libplacebo, quote_filter_path+++def shader_file(source: str) -> Path:+ directory = APP_TEMP / "vulkan-shaders"+ directory.mkdir(parents=True, exist_ok=True)+ path = directory / (hashlib.sha256(source.encode()).hexdigest() + ".hook")+ if not path.exists():+ # Identical contents make concurrent writers safe; each replacement is atomic.+ with tempfile.NamedTemporaryFile(dir=directory, suffix=".hook", delete=False) as stream:+ stream.write(source.encode())+ temporary = Path(stream.name)+ temporary.replace(path)+ return path+++def shader_filter(source: str, *, options: str = "") -> str:+ return libplacebo("custom_shader_path=" + quote_filter_path(shader_file(source))+ + (":" + options if options else ""))+++def filter_array(pixels: np.ndarray, graph: str, *, width: int | None = None,+ height: int | None = None, controller: JobController | None = None,+ selection: str | None = None) -> np.ndarray:+ if pixels.ndim != 3 or pixels.shape[2] != 4 or pixels.dtype not in (np.uint8, np.uint16):+ raise ValueError("Vulkan filtering requires uint8/uint16 RGBA pixels.")+ width, height = width or pixels.shape[1], height or pixels.shape[0]+ fmt = "rgba64le" if pixels.dtype == np.uint16 else "rgba"+ device = filter_device(selection or getattr(controller, "ffmpeg_device", None))+ command = [str(FFMPEG), "-v", "error", *device_args(device), "-f", "rawvideo",+ "-pixel_format", fmt, "-video_size", f"{pixels.shape[1]}x{pixels.shape[0]}",+ "-framerate", "1", "-i", "pipe:0", "-vf",+ "setparams=alpha_mode=premultiplied,hwupload," + graph + f",{libplacebo('format=' + fmt)},hwdownload,format={fmt}",+ "-frames:v", "1", "-c:v", "rawvideo", "-pix_fmt", fmt, "-f", "rawvideo", "pipe:1"]+ process = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE,+ stderr=subprocess.PIPE, creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))+ if controller:+ controller.register(process)+ try:+ data = np.ascontiguousarray(pixels).tobytes()+ while True:+ if controller and controller.cancel.is_set():+ raise Cancelled("Render stopped by user.")+ try:+ output, errors = process.communicate(input=data, timeout=0.2)+ break+ except subprocess.TimeoutExpired:+ data = None+ if process.returncode:+ raise RuntimeError("Vulkan filtering failed: " + errors.decode("utf-8", "replace")[-2500:])+ expected = width * height * 4 * pixels.dtype.itemsize+ if len(output) != expected:+ raise RuntimeError(f"Vulkan filter returned {len(output)} bytes; expected {expected}.")+ return np.frombuffer(output, dtype=pixels.dtype).reshape(height, width, 4).copy()+ finally:+ if process.poll() is None:+ process.kill()+ process.communicate()+ if controller:+ controller.unregister(process)+++def scaling_filter(width: int, height: int, method: str, *, source_size: tuple[int, int] | None = None,+ fit: bool = False) -> str:+ kernels = {"Spline36": "spline36", "Lanczos": "lanczos", "Bicubic": "bicubic",+ "Bilinear": "bilinear", "Nearest": "nearest"}+ if method in kernels:+ kernel = kernels[method]+ return libplacebo(f"w={width}:h={height}:upscaler={kernel}:downscaler={kernel}"+ + (":fit_mode=contain:fillcolor=black@1" if fit else ""))+ if method not in {"Area", "Lanczos4"}:+ raise ValueError(f"Unknown Vulkan scaling filter: {method!r}.")+ fit_width, fit_height, left, top = width, height, 0, 0+ if fit and source_size:+ scale = min(width / source_size[0], height / source_size[1])+ fit_width = max(1, min(width, round(source_size[0] * scale)))+ fit_height = max(1, min(height, round(source_size[1] * scale)))+ left, top = (width - fit_width) // 2, (height - fit_height) // 2+ header = f"""//!HOOK MAIN+//!BIND HOOKED+//!WIDTH {width}+//!HEIGHT {height}+vec4 pixel(ivec2 p) {{+ return HOOKED_tex((vec2(clamp(p, ivec2(0), ivec2(HOOKED_size)-1)) + 0.5) / HOOKED_size);+}}+vec4 hook() {{+ vec2 outpos = HOOKED_pos * vec2({width}.0, {height}.0) - vec2({left}.0, {top}.0);+ if (outpos.x < 0.0 || outpos.y < 0.0 || outpos.x >= {fit_width}.0 || outpos.y >= {fit_height}.0)+ return vec4(0.0, 0.0, 0.0, 1.0);+ vec2 ratio = HOOKED_size / vec2({fit_width}.0, {fit_height}.0);+"""+ if method == "Area":+ body = """+ vec2 lo = (outpos - 0.5) * ratio, hi = (outpos + 0.5) * ratio;+ vec4 sum = vec4(0.0); float total = 0.0;+ for (int y = int(floor(lo.y)); y < int(ceil(hi.y)); y++) {+ float wy = max(0.0, min(hi.y, float(y+1)) - max(lo.y, float(y)));+ for (int x = int(floor(lo.x)); x < int(ceil(hi.x)); x++) {+ float wx = max(0.0, min(hi.x, float(x+1)) - max(lo.x, float(x)));+ sum += pixel(ivec2(x,y)) * wx * wy; total += wx * wy;+ }+ }+ return sum / max(total, 1e-20);+}+"""+ else:+ header = header.replace("vec4 hook()", "float lanczos(float x) { x=abs(x); if(x<1e-6) return 1.0; if(x>=4.0) return 0.0; return sin(3.14159265*x)*sin(3.14159265*x/4.0)/(3.14159265*3.14159265*x*x/4.0); }\nvec4 hook()")+ body = """+ vec2 p = outpos * ratio - 0.5, support = max(ratio, vec2(1.0));+ vec4 sum = vec4(0.0); float total = 0.0;+ for(int y=int(ceil(p.y-4.0*support.y)); y<=int(floor(p.y+4.0*support.y)); y++) {+ float wy=lanczos((float(y)-p.y)/support.y);+ for(int x=int(ceil(p.x-4.0*support.x)); x<=int(floor(p.x+4.0*support.x)); x++) {+ float w=wy*lanczos((float(x)-p.x)/support.x);+ sum+=pixel(ivec2(x,y))*w; total+=w;+ }+ }+ return clamp(sum/max(total,1e-20),0.0,1.0);+}+"""+ return shader_filter(header + body, options=f"w={width}:h={height}:upscaler=nearest:downscaler=nearest")+++def resize_fit(pixels: np.ndarray, width: int, height: int, *, interpolation: str = "Lanczos4",+ controller: JobController | None = None) -> np.ndarray:+ if (pixels.shape[1], pixels.shape[0]) == (width, height):+ return np.ascontiguousarray(pixels)+ graph = scaling_filter(width, height, interpolation,+ source_size=(pixels.shape[1], pixels.shape[0]), fit=True)+ return filter_array(pixels, graph, width=width, height=height, controller=controller)diff --git a/src/core/ffmpeg/frames.py b/src/core/ffmpeg/frames.pynew file mode 100644index 0000000..bdb3764--- /dev/null+++ b/src/core/ffmpeg/frames.py@@ -0,0 +1,213 @@+"""Timestamped FFmpeg Vulkan codecs at host frame boundaries.++The bundled FFmpeg has Vulkan Video support that PyAV's libraries do not.+PyAV here only demuxes/muxes raw NUT packets; it never encodes compressed video.+"""+from __future__ import annotations++import subprocess+import threading+from fractions import Fraction+from pathlib import Path+from types import SimpleNamespace++import av+import numpy as np++from ..jobs import BoundedLogBuffer, Cancelled, drain_bounded_text+from ..paths import FFMPEG+from .nut import RawVideoPacketMuxer+from .vulkan import prepare_command, stream_info+++class _Reader:+ def __init__(self, pipe):+ self.pipe = pipe++ def read(self, size):+ return self.pipe.read(size)+++class VideoDecoder:+ def __init__(self, source, controller, *, pixel_format: str | None = None, selection=None, video_filter="", cwd=None):+ self.controller, self.container = controller, None+ info = stream_info(source)+ if pixel_format is None:+ source_format = info.get("pix_fmt", "yuv420p")+ # Keep the original layout when Vulkan can represent it. Conversion+ # to RGB/YUV required by a consumer is an explicit GPU operation.+ pixel_format = source_format if source_format in {"yuv420p", "yuv420p10le", "yuv422p10le", "gbrp10le", "rgba", "rgba64le", "nv12", "p010le"} else "rgba64le"+ command = [str(FFMPEG), "-v", "warning", "-xerror", "-copyts", "-noautorotate",+ "-i", str(source), "-map", "0:v:0", "-an", "-sn", "-dn", "-c:v", "rawvideo",+ *(["-vf", video_filter] if video_filter else []),+ "-pix_fmt", pixel_format, "-fps_mode", "passthrough", "-enc_time_base", "demux",+ "-f", "nut", "-write_index", "0", "pipe:1"]+ command = prepare_command(command, selection=selection or getattr(controller, "ffmpeg_device", None))+ self.logs = BoundedLogBuffer(max_tail=60)+ self.process = subprocess.Popen(command, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE,+ stderr=subprocess.PIPE, cwd=cwd,+ creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))+ controller.register(self.process)+ self.thread = threading.Thread(target=drain_bounded_text, args=(self.process.stderr, self.logs), daemon=True)+ self.thread.start()+ try:+ self.container = av.open(_Reader(self.process.stdout), format="nut")+ except BaseException:+ self.close()+ raise RuntimeError("FFmpeg decoder failed:\n" + "\n".join(self.logs.snapshot()))++ @property+ def streams(self):+ return self.container.streams++ def decode(self, *args, **kwargs):+ for frame in self.container.decode(*args, **kwargs):+ if self.controller.cancel.is_set():+ raise Cancelled("Render stopped by user.")+ yield frame+ self.process.wait(timeout=10)+ self.thread.join(timeout=2)+ if self.process.returncode:+ raise RuntimeError("FFmpeg decoder failed:\n" + "\n".join(self.logs.snapshot()))++ def close(self):+ if self.process.poll() is None:+ self.process.kill()+ self.process.wait(timeout=5)+ if self.container:+ self.container.close()+ self.container = None+ self.thread.join(timeout=2)+ self.controller.unregister(self.process)+ self.process.stdout.close()+ self.process.stderr.close()++ def __enter__(self):+ return self++ def __exit__(self, *_):+ self.close()+++def open_video_decoder(source, controller, *, pixel_format=None, selection=None, video_filter="", cwd=None):+ return VideoDecoder(source, controller, pixel_format=pixel_format, selection=selection, video_filter=video_filter, cwd=cwd)+++def packed_frame(frame) -> np.ndarray:+ """Copy logical rows, omitting padding; no pixel conversion takes place."""+ rows = []+ for index, plane in enumerate(frame.planes):+ components = [c for c in frame.format.components if c.plane == index]+ row_bytes = sum(c.width * ((c.bits + 7) // 8) for c in components)+ if not components or row_bytes > plane.line_size:+ raise ValueError(f"Unsupported raw frame layout: {frame.format.name}.")+ rows.append(np.ascontiguousarray(np.frombuffer(plane, dtype=np.uint8)+ .reshape(plane.height, plane.line_size)[:, :row_bytes]).reshape(-1))+ return np.concatenate(rows)+++class _CodecContext(SimpleNamespace):+ def open(self):+ pass # The CLI encoder is initialized with the first frame's layout.+++class _OutputStream:+ def __init__(self, codec, rate):+ self.codec, self.rate = codec, Fraction(rate)+ self.width = self.height = 0+ self.pix_fmt, self.time_base = "yuv420p", None+ self.codec_context = _CodecContext(options={}, bit_rate=0, time_base=None,+ colorspace=2, color_range=0, color_primaries=2, color_trc=2)++ def encode(self, frame=None):+ return () if frame is None else (frame,)+++class VideoOutput:+ """Small host pipeline adapter that feeds timestamped frames to CLI codecs."""+ def __init__(self, destination, controller, *, selection=None):+ self.destination, self.controller, self.selection = destination, controller, selection or getattr(controller, "ffmpeg_device", None)+ self.stream = self.process = self.writer = self.thread = None+ self.logs = BoundedLogBuffer(max_tail=60)+ self.closed = False++ def add_stream(self, codec, rate, *, hwaccel=None):+ if hwaccel is not None:+ raise ValueError("FFmpeg Vulkan output accepts host frames; CUDA-owned frames require their native transport.")+ if self.stream:+ raise ValueError("VideoOutput accepts one video stream.")+ self.stream = _OutputStream(codec, rate)+ return self.stream++ def _start(self, frame):+ s, ctx = self.stream, self.stream.codec_context+ options = []+ for key, value in ctx.options.items():+ options += ["-" + key, str(value)]+ if ctx.bit_rate:+ options += ["-b:v", str(ctx.bit_rate)]+ colors = []+ for key, flag in (("colorspace", "-colorspace"), ("color_range", "-color_range"),+ ("color_primaries", "-color_primaries"), ("color_trc", "-color_trc")):+ colors += [flag, str(getattr(ctx, key))]+ command = [str(FFMPEG), "-v", "warning", "-y", "-copyts", "-f", "nut", "-i", "pipe:0",+ "-map", "0:v:0", "-an", "-c:v", s.codec, *options, "-pix_fmt", s.pix_fmt,+ *colors, "-fps_mode", "passthrough", "-enc_time_base", "demux", str(self.destination)]+ input_matrix = 0 if frame.format.is_rgb else frame.colorspace if frame.colorspace != 2 else (9 if ctx.color_primaries == 9 else 1)+ tags = f"setparams=colorspace={input_matrix}:color_primaries={ctx.color_primaries}:color_trc={ctx.color_trc}:range={'full' if frame.format.is_rgb else 'limited'}"+ command[-1:-1] = ["-vf", tags]+ command = prepare_command(command, selection=self.selection, dimensions=(s.width, s.height), input_format=frame.format.name,+ rate=str(s.rate), time_base=str(ctx.time_base or s.time_base or frame.time_base))+ self.actual_encoder = command[command.index("-c:v") + 1]+ self.process = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.DEVNULL,+ stderr=subprocess.PIPE, creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))+ self.controller.register(self.process)+ self.thread = threading.Thread(target=drain_bounded_text, args=(self.process.stderr, self.logs), daemon=True)+ self.thread.start()+ self.writer = RawVideoPacketMuxer(self.process.stdin, width=s.width, height=s.height,+ rate=s.rate, time_base=ctx.time_base or s.time_base or frame.time_base,+ pix_fmt=frame.format.name)+ self.raw_format = frame.format.name++ def mux(self, frame):+ if self.closed:+ raise ValueError("Video encoder is closed.")+ if self.controller.cancel.is_set():+ raise Cancelled("Render stopped by user.")+ if not self.process:+ self._start(frame)+ if (frame.width, frame.height, frame.format.name) != (self.stream.width, self.stream.height, self.raw_format):+ raise ValueError("Host frame dimensions or format changed during encoding.")+ pts = round(Fraction(frame.pts) * frame.time_base / self.writer.time_base)+ duration = round(Fraction(frame.duration or 0) * frame.time_base / self.writer.time_base)+ try:+ self.writer.write(packed_frame(frame), pts, duration)+ except (OSError, av.error.FFmpegError) as exc:+ raise RuntimeError("FFmpeg encoder failed:\n" + "\n".join(self.logs.snapshot())) from exc++ def close(self):+ if self.closed:+ return+ self.closed = True+ if not self.process:+ return+ try:+ self.writer.close()+ self.process.stdin.close()+ while self.process.poll() is None:+ if self.controller.cancel.is_set():+ raise Cancelled("Render stopped by user.")+ try:+ self.process.wait(timeout=0.2)+ except subprocess.TimeoutExpired:+ continue+ self.thread.join(timeout=2)+ if self.process.returncode:+ raise RuntimeError("FFmpeg encoder failed:\n" + "\n".join(self.logs.snapshot()))+ finally:+ if self.process.poll() is None:+ self.process.kill()+ self.process.wait(timeout=5)+ self.controller.unregister(self.process)+ self.thread.join(timeout=2)+ self.process.stderr.close()diff --git a/src/core/ffmpeg/preview.py b/src/core/ffmpeg/preview.pyindex 99eb422..7ba5bc6 100644--- a/src/core/ffmpeg/preview.py+++ b/src/core/ffmpeg/preview.py@@ -1,355 +1,207 @@-from __future__ import annotations--import subprocess-from pathlib import Path--from .. import app_log+from __future__ import annotations++import subprocess+from .vulkan import prepare_command+from pathlib import Path++from .. import app_logfrom ..paths import FFMPEG-from .codecs import _base_codec--PREVIEW_ENCODING_CHOICES = ("Auto", "Always H.264", "Disabled")-DEFAULT_PREVIEW_ENCODING = "Auto"---def normalize_preview_encoding(value: object) -> str:- """Return a valid preview-encoding mode, defaulting to Auto."""- if isinstance(value, str) and value.strip() in PREVIEW_ENCODING_CHOICES:- return value.strip()- return DEFAULT_PREVIEW_ENCODING---def is_user_playable_request(codec: str, container: str) -> bool:- """Pre-check whether the requested encode settings are browser-playable.-- Strict definition: MP4 container + H.264 base codec (plain or NVENC).- Used to pick the encode path without paying for a probe first.- """- try:- if container != "MP4":- return False- return _base_codec(codec) == "H.264"- except Exception:- return False---def resolve_preview_codec(- requested_codec: str, requested_container: str, mode: object-) -> tuple[str, str]:- """Return the (codec, container) to encode a truncated preview with."""- normalized = normalize_preview_encoding(mode)- if normalized == "Disabled":- return requested_codec, requested_container- if normalized == "Always H.264":- return "H.264", "MP4"- # Auto: reuse the user's settings when they are already browser-playable,- # otherwise fall back to the compatible H.264/MP4 preview.- if is_user_playable_request(requested_codec, requested_container):- return requested_codec, requested_container- return "H.264", "MP4"---def wants_compat_preview(- requested_codec: str, requested_container: str, mode: object-) -> bool:- """True when a truncated preview must use the forced H.264 SDR path."""- normalized = normalize_preview_encoding(mode)- if normalized == "Disabled":- return False- if normalized == "Always H.264":- return True- return not is_user_playable_request(requested_codec, requested_container)--def is_browser_playable(path: str | Path) -> bool:- """Probe the actual output file: playable iff MP4 + H.264 video stream."""+LOSSLESS_PREVIEW_CODEC = "FFV1 Lossless RGB 10-bit"+++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 and not single_frame and not length_seconds:+ return str(src)from .probe import probe_video-- candidate = Path(path)- if candidate.suffix.lower() != ".mp4":- return False- try:- metadata = probe_video(candidate, count_mode="metadata")- except Exception:- return False- codec = str(metadata.get("codec") or "").lower()- if codec not in ("h264", "avc"):- return False- container_format = str(metadata.get("format") or "").lower()- # ffprobe reports e.g. "mov,mp4,m4a,3gp,3g2,mj2" for MP4 files.- if "mp4" not in container_format:- return False- return True---def make_browser_preview(- source: str | Path,- dest_dir: str | Path | None = None,- controller=None,- *, sdr_filter: str | None = None,- max_seconds: float | None = None,- max_width: int | None = None,-) -> str:- """Transcode an existing result file to a browser-playable H.264 MP4.-- Returns the new preview path as a string. Raises RuntimeError on failure.- """- from ..paths import OUTPUTS- from ..jobs import current_job_controller- from ..disk_paths import OutputFile-- controller = controller or current_job_controller()-- src = Path(source)- if not src.is_file():- raise FileNotFoundError(src)- out_dir = Path(dest_dir) if dest_dir is not None else OUTPUTS- out_dir.mkdir(parents=True, exist_ok=True)- dest = out_dir / f"{src.stem}_BROWSERPREVIEW.mp4"- counter = 1- while dest.exists():- counter += 1- dest = out_dir / f"{src.stem}_BROWSERPREVIEW_{counter}.mp4"- output_file = OutputFile(dest)- filters: list[str] = []- if sdr_filter:- filters.append(sdr_filter)- if max_width is not None and max_width > 0:- filters.append(f"scale=if(gt(iw\\,{int(max_width)})\\,{int(max_width)}\\,iw):-2")- command = [- str(FFMPEG),- "-hide_banner",- "-loglevel",- "warning",- "-y",- "-i",- str(src),- *(["-t", f"{float(max_seconds):.6f}"] if max_seconds is not None and max_seconds > 0 else []),- "-map",- "0:v:0",- "-map",- "0:a?",- *(["-vf", ",".join(filters)] if filters else []),- *(["-color_primaries", "bt709", "-color_trc", "bt709", "-colorspace", "bt709", "-color_range", "tv"] if sdr_filter else []),- "-c:v",- "libx264",- "-preset",- "veryfast",- "-crf",- "18",- "-pix_fmt",- "yuv420p",- "-c:a",- "aac",- "-b:a",- "192k",- "-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)+ from ..jobs import Cancelled+ if controller is not None and controller.cancel.is_set():+ raise Cancelled("Preview cancelled.")+ metadata = probe_video(src, count_mode="metadata", controller=controller)+ # 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.mkv" if single_frame else "_PLAYHEAD.mkv"+ dest = out_dir / f"{src.stem}{suffix}"+ counter = 1+ while dest.exists():+ counter += 1+ dest = out_dir / f"{src.stem}{suffix.replace('.mkv', f'_{counter}.mkv')}"+ 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}"]+ color_args = []+ for key, flag in (("color_primaries", "-color_primaries"),+ ("color_transfer", "-color_trc")):+ value = metadata.get(key)+ if value and value != "unknown":+ color_args.extend((flag, str(value)))+ command += [+ "-map", "0:v:0",+ "-an", "-map_metadata", "0",+ "-c:v", "ffv1", "-level", "3", "-slicecrc", "1",+ "-pix_fmt", "gbrp10le", "-colorspace", "0", "-color_range", "pc",+ *color_args,+ str(output_file.temporary),+ ]+ process = None+ try:+ command = prepare_command(command)+ 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", "browser preview transcode failed", (stderr or "")[-500:])- raise RuntimeError("Browser preview transcode failed:\n" + (stderr or "")[-4000:])- if not is_browser_playable(output_file.temporary):- raise RuntimeError("Browser preview transcode produced an unplayable file.")if controller is not None and controller.cancel.is_set():- from ..jobs import Cancelledraise 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()+ 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.")+ 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 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``.+def decode_preview_frame(source: str | Path, *, controller=None):+ """Return a full-resolution 16-bit RGBA still without a video encode.- 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.+ HDR is mapped to the display's SDR image surface only. The cached clip+ retains its original samples and HDR signaling for video playback."""- from ..disk_paths import OutputFile- from ..jobs import current_job_controller+ import numpy as np+ from ..jobs import Cancelled, current_job_controller+ from .probe import probe_videocontroller = 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 and controller.cancel.is_set():+ raise Cancelled("Preview cancelled.")+ metadata = probe_video(source, count_mode="metadata", controller=controller)+ filters = []+ if metadata.get("hdr"):+ filters.append(+ "zscale=transfer=linear:npl=100,format=gbrpf32le,"+ "zscale=primaries=bt709,tonemap=mobius:desat=2,"+ "zscale=transfer=bt709:matrix=gbr:range=full")- 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.")+ command = [str(FFMPEG), "-hide_banner", "-loglevel", "error",+ "-i", str(source), "-map", "0:v:0", "-frames:v", "1", "-an",+ *(["-vf", ",".join(filters)] if filters else []),+ "-f", "rawvideo", "-pix_fmt", "rgba64le", "pipe:1"]+ command = prepare_command(command, selection=getattr(controller, "ffmpeg_device", None))+ process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE,+ creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))+ if controller is not None:+ controller.register(process)+ try:+ pixels, error = process.communicate()if controller is not None and controller.cancel.is_set():- from ..jobs import Cancelledraise Cancelled("Preview cancelled.")- output_file.publish()+ if process.returncode:+ raise RuntimeError("Preview frame decoding failed: " + error.decode("utf-8", "replace")[-2000:])+ width, height = int(metadata["width"]), int(metadata["height"])+ if len(pixels) != width * height * 8:+ raise RuntimeError("Preview frame has unexpected dimensions.")+ return np.frombuffer(pixels, dtype="<u2").reshape(height, width, 4)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)+ if process.poll() is None:+ process.terminate()+ process.communicate()+ if controller is not None:+ controller.unregister(process)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,- controller=None,- *, bounded_proxy: bool = False,-) -> tuple[str | None, bool]:- """Decide which file the final-render in-app player should show.-- Returns (display_path, used_derivative). Applies the agreed policy:- - Always H.264: current behavior (MP4 result only, else no preview).- - Disabled: always show the actual file (even MKV/MOV).- - Auto: probe the result; show directly when playable, else transcode- one H.264 derivative and show that.- """- if not result_path:- return None, False- normalized = normalize_preview_encoding(mode)- candidate = str(result_path)- if normalized == "Disabled":- return candidate, False- if normalized == "Always H.264":- if Path(candidate).suffix.lower() == ".mp4":- return candidate, False- return None, False- # Auto- try:- if is_browser_playable(candidate):- return candidate, False- except Exception:- pass- try:- derived = make_browser_preview(- candidate, controller=controller,- max_seconds=12.0 if bounded_proxy else None,- max_width=1280 if bounded_proxy else None,- )- except Exception:- # Never break the render status path: fall back to no in-app preview- # (the real file is still in the download list).- return None, False- return derived, True+ 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",+ ]+ command = prepare_command(command, selection=getattr(controller, "ffmpeg_device", None))+ 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)diff --git a/src/core/ffmpeg/probe.py b/src/core/ffmpeg/probe.pyindex fb0f53f..44d8dab 100644--- a/src/core/ffmpeg/probe.py+++ b/src/core/ffmpeg/probe.py@@ -1,255 +1,263 @@-from __future__ import annotations--import json-import math-import os-import subprocess-import tempfile-from fractions import Fraction-from pathlib import Path--import av--from ..paths import FFPROBE-from ..jobs import Cancelled, JobController-from .. import app_log--def _run_json(- command: list[str], *, strict_decode: bool = False,- controller: JobController | None = None,-) -> dict:- if controller is not None and controller.cancel.is_set():- raise Cancelled("Render stopped by user.")- # ffprobe can report decoding errors and still exit with code zero. Keep its- # error output outside RAM, and retain a bounded excerpt for diagnostics.- with tempfile.TemporaryFile() as errors:- process = subprocess.Popen(- command, stdout=subprocess.PIPE, stderr=errors,- creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),- )- if controller is not None:- controller.register(process)- try:- while True:- if controller is not None and controller.cancel.is_set():- raise Cancelled("Render stopped by user.")- try:- stdout, _ = process.communicate(timeout=0.2)- break- except subprocess.TimeoutExpired:- continue- if controller is not None and controller.cancel.is_set():- raise Cancelled("Render stopped by user.")- size = errors.seek(0, os.SEEK_END)- errors.seek(max(0, size - 8000))- details = errors.read().decode("utf-8", "replace").strip()- if strict_decode and size:- app_log.error("ffprobe", "source decoding failed", details[-500:])- raise RuntimeError("Source decoding failed during frame-count verification:\n" + details)- if process.returncode:- app_log.error("ffprobe", "media probe failed", details[-500:])- raise RuntimeError(details or "Media probe failed")- return json.loads(stdout)- finally:- if process.poll() is None:- process.terminate()- try:- process.wait(timeout=5)- except subprocess.TimeoutExpired:- process.kill()- process.wait(timeout=5)- if process.stdout is not None:- process.stdout.close()- if controller is not None:- controller.unregister(process)----def _positive_float(value: object) -> float:- try:- number = float(value)- except (ValueError, TypeError, OverflowError):- return 0.0- return number if math.isfinite(number) and number > 0 else 0.0--def _positive_count(value: object) -> int:- try:- return max(0, int(value))- except (ValueError, TypeError, OverflowError):- return 0---def _sampled_packet_timeline_is_cfr(- path: str | os.PathLike[str], time_base: Fraction,- controller: JobController | None,-) -> bool:- """Reject VFR timelines that container-level average/nominal rates hide.-- Packet PTS values are sorted to remove codec reordering. Read past the- portion being tested: the final packets of a bounded B-frame sample can- contain a later PTS while an earlier PTS is still outside the sample.- """- data = _run_json([- str(FFPROBE), "-v", "error", "-select_streams", "v:0",- "-read_intervals", "%+#160", "-show_packets", "-show_entries",- "packet=pts", "-of", "json", str(path),- ], controller=controller)- packets = data.get("packets") or []- timestamps = sorted({int(packet["pts"]) for packet in packets- if packet.get("pts") not in {None, "N/A"}})- if len(packets) >= 160:- timestamps = timestamps[:-16]- deltas = [b - a for a, b in zip(timestamps, timestamps[1:]) if b > a]- if len(deltas) < 2:- return True- # CFR timestamp quantization may alternate adjacent deltas by one time-base- # tick. A wider spread is an actual cadence change.- tolerance_ticks = max(1, int(round(float(Fraction(1, 1000000) / time_base))))- return max(deltas) - min(deltas) <= tolerance_ticks---def probe_video(- path: str | os.PathLike[str], *, count_mode: str = "exact",- strict_decode: bool = False, controller: JobController | None = None,- inspect_timestamps: bool = False,-) -> dict:- """Probe video metadata, optionally counting decoded frames or packets.-- The default remains the legacy exact decoded-frame count for external callers.- Conversion paths use metadata first and pay for exact counting only as fallback.- Strict decoding rejects decoder errors and unavailable decoded counts, even- when ffprobe exits successfully or the container declares a positive count.- """- if count_mode not in {"metadata", "exact", "packets"}:- raise ValueError(f"Unknown video count mode: {count_mode!r}.")- if strict_decode and count_mode != "exact":- raise ValueError("Strict decoding requires count_mode='exact'.")- count_args = {- "metadata": [],- "exact": ["-count_frames"],- "packets": ["-count_packets"],- }[count_mode]- data = _run_json(- [- str(FFPROBE),- "-v",- "error",- *count_args,- "-select_streams",- "v:0",- "-show_entries",- "stream=index,codec_name,pix_fmt,bits_per_raw_sample,width,height,avg_frame_rate,r_frame_rate,time_base,duration,nb_frames,nb_read_frames,nb_read_packets,color_range,color_primaries,color_transfer,color_space,chroma_location:stream_tags=rotate:stream_side_data=rotation",- "-show_entries",- "format=duration,format_name",- "-of",- "json",- str(path),- ], strict_decode=strict_decode, controller=controller,- )- streams = data.get("streams") or []- if not streams:- raise ValueError("The selected file contains no decodable video stream.")- stream = streams[0]- rotation = int((stream.get("tags") or {}).get("rotate", 0) or 0)- for side in stream.get("side_data_list") or []:- if "rotation" in side:- rotation = int(side["rotation"] or 0)- rotation %= 360- width, height = int(stream["width"]), int(stream["height"])- if rotation in (90, 270):- width, height = height, width- declared_frames = _positive_count(stream.get("nb_frames"))+from __future__ import annotations++import json+import math+import os+import subprocess+import tempfile+from fractions import Fraction+from pathlib import Path++import av++from ..paths import FFPROBE+from ..jobs import Cancelled, JobController+from .. import app_log++def _run_json(+ command: list[str], *, strict_decode: bool = False,+ controller: JobController | None = None,+) -> dict:+ if controller is not None and controller.cancel.is_set():+ raise Cancelled("Render stopped by user.")+ # ffprobe can report decoding errors and still exit with code zero. Keep its+ # error output outside RAM, and retain a bounded excerpt for diagnostics.+ with tempfile.TemporaryFile() as errors:+ process = subprocess.Popen(+ command, stdout=subprocess.PIPE, stderr=errors,+ creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),+ )+ if controller is not None:+ controller.register(process)+ try:+ while True:+ if controller is not None and controller.cancel.is_set():+ raise Cancelled("Render stopped by user.")+ try:+ stdout, _ = process.communicate(timeout=0.2)+ break+ except subprocess.TimeoutExpired:+ continue+ if controller is not None and controller.cancel.is_set():+ raise Cancelled("Render stopped by user.")+ size = errors.seek(0, os.SEEK_END)+ errors.seek(max(0, size - 8000))+ details = errors.read().decode("utf-8", "replace").strip()+ if strict_decode and size:+ app_log.error("ffprobe", "source decoding failed", details[-500:])+ raise RuntimeError("Source decoding failed during frame-count verification:\n" + details)+ if process.returncode:+ app_log.error("ffprobe", "media probe failed", details[-500:])+ raise RuntimeError(details or "Media probe failed")+ return json.loads(stdout)+ finally:+ if process.poll() is None:+ process.terminate()+ try:+ process.wait(timeout=5)+ except subprocess.TimeoutExpired:+ process.kill()+ process.wait(timeout=5)+ if process.stdout is not None:+ process.stdout.close()+ if controller is not None:+ controller.unregister(process)++++def _positive_float(value: object) -> float:+ try:+ number = float(value)+ except (ValueError, TypeError, OverflowError):+ return 0.0+ return number if math.isfinite(number) and number > 0 else 0.0++def _positive_count(value: object) -> int:+ try:+ return max(0, int(value))+ except (ValueError, TypeError, OverflowError):+ return 0+++def _sampled_packet_timeline_is_cfr(+ path: str | os.PathLike[str], time_base: Fraction,+ controller: JobController | None,+) -> bool:+ """Reject VFR timelines that container-level average/nominal rates hide.++ Packet PTS values are sorted to remove codec reordering. Read past the+ portion being tested: the final packets of a bounded B-frame sample can+ contain a later PTS while an earlier PTS is still outside the sample.+ """+ data = _run_json([+ str(FFPROBE), "-v", "error", "-select_streams", "v:0",+ "-read_intervals", "%+#160", "-show_packets", "-show_entries",+ "packet=pts", "-of", "json", str(path),+ ], controller=controller)+ packets = data.get("packets") or []+ timestamps = sorted({int(packet["pts"]) for packet in packets+ if packet.get("pts") not in {None, "N/A"}})+ if len(packets) >= 160:+ timestamps = timestamps[:-16]+ deltas = [b - a for a, b in zip(timestamps, timestamps[1:]) if b > a]+ if len(deltas) < 2:+ return True+ # CFR timestamp quantization may alternate adjacent deltas by one time-base+ # tick. A wider spread is an actual cadence change.+ tolerance_ticks = max(1, int(round(float(Fraction(1, 1000000) / time_base))))+ return max(deltas) - min(deltas) <= tolerance_ticks+++def probe_video(+ path: str | os.PathLike[str], *, count_mode: str = "exact",+ strict_decode: bool = False, controller: JobController | None = None,+ inspect_timestamps: bool = False,+) -> dict:+ """Probe video metadata, optionally counting decoded frames or packets.++ The default remains the legacy exact decoded-frame count for external callers.+ Conversion paths use metadata first and pay for exact counting only as fallback.+ Strict decoding rejects decoder errors and unavailable decoded counts, even+ when ffprobe exits successfully or the container declares a positive count.+ """+ if count_mode not in {"metadata", "exact", "packets"}:+ raise ValueError(f"Unknown video count mode: {count_mode!r}.")+ if strict_decode and count_mode != "exact":+ raise ValueError("Strict decoding requires count_mode='exact'.")+ count_args = {+ "metadata": [],+ "exact": [],+ "packets": ["-count_packets"],+ }[count_mode]+ data = _run_json(+ [+ str(FFPROBE),+ "-v",+ "error",+ *count_args,+ "-select_streams",+ "v:0",+ "-show_entries",+ "stream=index,codec_name,pix_fmt,bits_per_raw_sample,width,height,avg_frame_rate,r_frame_rate,time_base,duration,nb_frames,nb_read_frames,nb_read_packets,color_range,color_primaries,color_transfer,color_space,chroma_location:stream_tags=rotate:stream_side_data=rotation",+ "-show_entries",+ "format=duration,format_name",+ "-of",+ "json",+ str(path),+ ], strict_decode=strict_decode, controller=controller,+ )+ streams = data.get("streams") or []+ if not streams:+ raise ValueError("The selected file contains no decodable video stream.")+ stream = streams[0]+ rotation = int((stream.get("tags") or {}).get("rotate", 0) or 0)+ for side in stream.get("side_data_list") or []:+ if "rotation" in side:+ rotation = int(side["rotation"] or 0)+ rotation %= 360+ width, height = int(stream["width"]), int(stream["height"])+ if rotation in (90, 270):+ width, height = height, width+ declared_frames = _positive_count(stream.get("nb_frames"))decoded_frames = _positive_count(stream.get("nb_read_frames"))- packet_frames = _positive_count(stream.get("nb_read_packets"))- if count_mode == "packets":- frames = packet_frames or declared_frames- frame_count_source = "packets" if packet_frames else "metadata"- elif count_mode == "exact":- frames = decoded_frames if strict_decode else (decoded_frames or declared_frames)- frame_count_source = "decoded" if decoded_frames else "metadata"- else:- frames = declared_frames- frame_count_source = "metadata" if frames > 0 else "unavailable"- if count_mode == "exact" and frames <= 0:- raise ValueError("Could not determine an exact frame count for this video.")- average_rate_text = stream.get("avg_frame_rate") or "0/0"- nominal_rate_text = stream.get("r_frame_rate") or "0/0"- rate_text = average_rate_text if average_rate_text != "0/0" else nominal_rate_text- if rate_text == "0/0":- rate_text = "30/1"- rate = Fraction(rate_text) if rate_text != "0/0" else Fraction(30, 1)- nominal_rate = (- Fraction(nominal_rate_text)- if nominal_rate_text != "0/0"- else rate- )- time_base = Fraction(stream.get("time_base") or "1/1000")- cfr = rate == nominal_rate- if cfr and inspect_timestamps:- cfr = _sampled_packet_timeline_is_cfr(path, time_base, controller)- transfer = stream.get("color_transfer") or "unknown"- primaries = stream.get("color_primaries") or "unknown"- color_space = stream.get("color_space") or "unknown"- color_range = stream.get("color_range") or "unknown"- pixel_format = stream.get("pix_fmt") or "unknown"- try:- depth = max(component.bits for component in av.VideoFormat(pixel_format).components)- except (ValueError, TypeError):- try:- depth = int(stream.get("bits_per_raw_sample") or 8)- except (TypeError, ValueError):- depth = 8- format_duration = _positive_float((data.get("format") or {}).get("duration"))- stream_duration = _positive_float(stream.get("duration"))- return {- "width": width,- "height": height,- "coded_width": int(stream["width"]),- "coded_height": int(stream["height"]),- "rotation": rotation,- "frames": frames,- "frame_count_source": frame_count_source,- "fps": float(rate),- "rate": rate,- "nominal_rate": nominal_rate,- "cfr": cfr,- "time_base": time_base,- "duration": format_duration or stream_duration,- "video_duration": stream_duration or format_duration,- "video_stream_duration": stream_duration,- "codec": stream.get("codec_name") or "unknown",- "pixel_format": pixel_format,- "depth": depth,- "format": (data.get("format") or {}).get("format_name") or "unknown",- "color_transfer": transfer,- "color_primaries": primaries,- "color_space": color_space,- "color_range": color_range,- "chroma_location": stream.get("chroma_location") or "unknown",- "hdr": transfer in {"smpte2084", "arib-std-b67"},- }--def preview_frame_count(source: Path, seconds: float) -> int:- """Count frames whose presentation times fall within the opening interval."""- container = av.open(str(source))- try:- stream = container.streams.video[0]- rate = float(stream.average_rate or 30)- first_time: float | None = None- count = 0- for frame in container.decode(stream):- timestamp = (- float(frame.pts * stream.time_base)- if frame.pts is not None and stream.time_base is not None- else count / rate- )- if first_time is None:- first_time = timestamp- if count and timestamp - first_time >= seconds:- break- count += 1- if count == 0:- raise RuntimeError("The input video contains no decodable preview frames.")- return count- finally:- container.close()+ if count_mode == "exact":+ from .frames import open_video_decoder+ counter_controller = controller or JobController()+ with open_video_decoder(path, counter_controller, pixel_format="rgba",+ video_filter="scale=2:2:flags=neighbor") as decoded:+ decoded_frames = sum(1 for _ in decoded.decode(decoded.streams.video[0]))+ packet_frames = _positive_count(stream.get("nb_read_packets"))+ if count_mode == "packets":+ frames = packet_frames or declared_frames+ frame_count_source = "packets" if packet_frames else "metadata"+ elif count_mode == "exact":+ frames = decoded_frames if strict_decode else (decoded_frames or declared_frames)+ frame_count_source = "decoded" if decoded_frames else "metadata"+ else:+ frames = declared_frames+ frame_count_source = "metadata" if frames > 0 else "unavailable"+ if count_mode == "exact" and frames <= 0:+ raise ValueError("Could not determine an exact frame count for this video.")+ average_rate_text = stream.get("avg_frame_rate") or "0/0"+ nominal_rate_text = stream.get("r_frame_rate") or "0/0"+ rate_text = average_rate_text if average_rate_text != "0/0" else nominal_rate_text+ if rate_text == "0/0":+ rate_text = "30/1"+ rate = Fraction(rate_text) if rate_text != "0/0" else Fraction(30, 1)+ nominal_rate = (+ Fraction(nominal_rate_text)+ if nominal_rate_text != "0/0"+ else rate+ )+ time_base = Fraction(stream.get("time_base") or "1/1000")+ cfr = rate == nominal_rate+ if cfr and inspect_timestamps:+ cfr = _sampled_packet_timeline_is_cfr(path, time_base, controller)+ transfer = stream.get("color_transfer") or "unknown"+ primaries = stream.get("color_primaries") or "unknown"+ color_space = stream.get("color_space") or "unknown"+ color_range = stream.get("color_range") or "unknown"+ pixel_format = stream.get("pix_fmt") or "unknown"+ try:+ depth = max(component.bits for component in av.VideoFormat(pixel_format).components)+ except (ValueError, TypeError):+ try:+ depth = int(stream.get("bits_per_raw_sample") or 8)+ except (TypeError, ValueError):+ depth = 8+ format_duration = _positive_float((data.get("format") or {}).get("duration"))+ stream_duration = _positive_float(stream.get("duration"))+ return {+ "width": width,+ "height": height,+ "coded_width": int(stream["width"]),+ "coded_height": int(stream["height"]),+ "rotation": rotation,+ "frames": frames,+ "frame_count_source": frame_count_source,+ "fps": float(rate),+ "rate": rate,+ "nominal_rate": nominal_rate,+ "cfr": cfr,+ "time_base": time_base,+ "duration": format_duration or stream_duration,+ "video_duration": stream_duration or format_duration,+ "video_stream_duration": stream_duration,+ "codec": stream.get("codec_name") or "unknown",+ "pixel_format": pixel_format,+ "depth": depth,+ "format": (data.get("format") or {}).get("format_name") or "unknown",+ "color_transfer": transfer,+ "color_primaries": primaries,+ "color_space": color_space,+ "color_range": color_range,+ "chroma_location": stream.get("chroma_location") or "unknown",+ "hdr": transfer in {"smpte2084", "arib-std-b67"},+ }++def preview_frame_count(source: Path, seconds: float) -> int:+ """Count frames whose presentation times fall within the opening interval."""+ from .frames import open_video_decoder+ from ..jobs import JobController+ container = open_video_decoder(source, JobController())+ try:+ stream = container.streams.video[0]+ rate = float(stream.average_rate or 30)+ first_time: float | None = None+ count = 0+ for frame in container.decode(stream):+ timestamp = (+ float(frame.pts * stream.time_base)+ if frame.pts is not None and stream.time_base is not None+ else count / rate+ )+ if first_time is None:+ first_time = timestamp+ if count and timestamp - first_time >= seconds:+ break+ count += 1+ if count == 0:+ raise RuntimeError("The input video contains no decodable preview frames.")+ return count+ finally:+ container.close()diff --git a/src/core/ffmpeg/progress.py b/src/core/ffmpeg/progress.pynew file mode 100644index 0000000..091dc53--- /dev/null+++ b/src/core/ffmpeg/progress.py@@ -0,0 +1,140 @@+"""Live FFmpeg work counters, independent of its human-readable stderr logs."""+from __future__ import annotations++import math+import queue+import subprocess+import tempfile+import threading+from pathlib import Path+from typing import Callable++from ..jobs import Cancelled, JobController+++def _number(value) -> float:+ try:+ number = float(value)+ return max(0.0, number) if math.isfinite(number) else 0.0+ except (TypeError, ValueError, OverflowError):+ return 0.0+++class VideoProgress:+ """Parse complete -progress records using frames, or timestamps for VFR/MKV.++ Metadata probing never decodes the source to count frames. When a container+ has no declared count, duration supplies the fraction and FPS supplies only+ an estimated total for the queue's frame/rate readout.+ """++ def __init__(self, metadata: dict | None, label: str):+ metadata = metadata or {}+ self.label = label+ self.frames = int(_number(metadata.get("frames")))+ self.duration = _number(metadata.get("video_duration")) or _number(metadata.get("duration"))+ self.estimated_frames = self.frames or round(self.duration * _number(metadata.get("fps")))+ self.record: dict[str, str] = {}+ self.fraction = 0.0+ self.processed = 0+ self.seconds = 0.0+ self.last_update: tuple[float, str] | None = None++ def feed(self, raw: bytes) -> tuple[float, str] | None:+ key, separator, value = raw.decode("utf-8", "replace").strip().partition("=")+ if not separator:+ return None+ self.record[key] = value+ if key != "progress":+ return None+ record, self.record = self.record, {}+ self.processed = max(self.processed, int(_number(record.get("frame"))))+ # Both out_time_us and the older out_time_ms are microseconds in FFmpeg.+ seconds = _number(record.get("out_time_us") or record.get("out_time_ms")) / 1_000_000+ if not seconds:+ parts = record.get("out_time", "").split(":")+ if len(parts) == 3 and not parts[0].startswith("-"):+ seconds = _number(parts[0]) * 3600 + _number(parts[1]) * 60 + _number(parts[2])+ self.seconds = max(self.seconds, seconds)+ if self.frames:+ fraction = self.processed / self.frames+ elif self.duration:+ fraction = self.seconds / self.duration+ else:+ fraction = 0.0+ # Even progress=end is sent before FFmpeg has returned successfully.+ self.fraction = max(self.fraction, min(.99, fraction))+ detail = f"{self.label}: {self.processed:,}"+ if self.estimated_frames:+ detail += f" / {self.estimated_frames:,}"+ detail += " frames"+ if not self.frames and self.estimated_frames:+ detail += " (estimated total)"+ update = (self.fraction, detail)+ if update == self.last_update:+ return None+ self.last_update = update+ return update+++def run_with_progress(command: list[str], controller: JobController, label: str,+ progress: Callable[[float, str], None], *, metadata: dict | None = None,+ cwd: Path | None = None) -> None:+ """Drain machine progress live while retaining stderr and prompt cancellation.++ The reader only queues records. The render thread invokes callbacks, so a+ finished stage cannot leave late events overwriting the following stage.+ """+ if controller.cancel.is_set():+ raise Cancelled("Render stopped by user.")+ command = [command[0], "-nostdin", "-nostats", "-stats_period", "0.2",+ "-progress", "pipe:1", *command[1:]]+ tracker = VideoProgress(metadata, label)+ updates: queue.SimpleQueue[tuple[float, str]] = queue.SimpleQueue()+ reader_done = threading.Event()+ with tempfile.TemporaryFile() as errors:+ process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=errors,+ stdin=subprocess.DEVNULL, cwd=cwd,+ creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))+ controller.register(process)++ def read_progress():+ try:+ for raw in iter(process.stdout.readline, b""):+ update = tracker.feed(raw)+ if update is not None:+ updates.put(update)+ finally:+ reader_done.set()++ reader = threading.Thread(target=read_progress, name="ffmpeg-progress", daemon=True)+ reader.start()+ try:+ progress(0.0, label)+ while not (reader_done.is_set() and process.poll() is not None):+ if controller.cancel.is_set():+ raise Cancelled("Render stopped by user.")+ try:+ progress(*updates.get(timeout=.05))+ except queue.Empty:+ pass+ while not updates.empty():+ if controller.cancel.is_set():+ raise Cancelled("Render stopped by user.")+ progress(*updates.get_nowait())+ if controller.cancel.is_set():+ raise Cancelled("Render stopped by user.")+ if process.wait():+ errors.seek(0, 2)+ errors.seek(max(0, errors.tell() - 2500))+ raise RuntimeError(f"{label} failed: {errors.read().decode('utf-8', 'replace')}")+ progress(1.0, f"{label} complete")+ finally:+ try:+ if process.poll() is None:+ process.kill()+ process.wait(timeout=5)+ finally:+ controller.unregister(process)+ reader.join(timeout=2)+ process.stdout.close()diff --git a/src/core/ffmpeg/sharpening.py b/src/core/ffmpeg/sharpening.pynew file mode 100644index 0000000..9081389--- /dev/null+++ b/src/core/ffmpeg/sharpening.py@@ -0,0 +1,104 @@+"""Vendor-neutral GLSL implementations of CAS and NIS sharpen-only kernels.++CAS: Copyright (C) 2024 Advanced Micro Devices, Inc.+NIS: Copyright (c) 2022 NVIDIA CORPORATION & AFFILIATES.+See src/desktop/AMD-FidelityFX-CAS-LICENSE.txt and NVIDIA-NIS-LICENSE.txt.+"""+from __future__ import annotations++import numpy as np++from .filters import filter_array, shader_filter+++def sharpening_filter(method: str, sharpness: int, transfer: str = "srgb", *, depth: int = 16) -> str:+ if isinstance(sharpness, bool) or not isinstance(sharpness, int) or not 0 <= sharpness <= 100:+ raise ValueError("Sharpness must be an integer from 0 to 100.")+ if transfer not in {"srgb", "bt709", "linear"}:+ raise ValueError("Unsupported sharpening transfer function.")+ source = """//!HOOK MAIN+//!BIND HOOKED+vec4 pixel(ivec2 d) {+ vec2 p = clamp(floor(HOOKED_pos * HOOKED_size) + vec2(d), vec2(0.0), HOOKED_size - 1.0);+ return HOOKED_tex((p + 0.5) / HOOKED_size);+}+"""+ if depth == 8:+ source = source.replace("return HOOKED_tex((p + 0.5) / HOOKED_size);", "return round(HOOKED_tex((p + 0.5) / HOOKED_size) * 255.0) / 255.0;")+ if method == "AMD CAS":+ if transfer == "srgb":+ source += "vec3 lin(vec3 c) { return mix(pow((c+0.055)/1.055,vec3(2.4)),c/12.92,lessThanEqual(c,vec3(0.04045))); }\nvec3 enc(vec3 c) { return mix(1.055*pow(c,vec3(1.0/2.4))-0.055,c*12.92,lessThanEqual(c,vec3(0.0031308))); }\n"+ elif transfer == "bt709":+ source += "vec3 lin(vec3 c) { return mix(pow((c+0.099)/1.099,vec3(1.0/0.45)),c/4.5,lessThan(c,vec3(0.081))); }\nvec3 enc(vec3 c) { return mix(1.099*pow(c,vec3(0.45))-0.099,c*4.5,lessThan(c,vec3(0.018))); }\n"+ else:+ source += "vec3 lin(vec3 c) { return c; } vec3 enc(vec3 c) { return c; }\n"+ source += f"""vec4 hook() {{+ vec4 b=pixel(ivec2(0,-1)),d=pixel(ivec2(-1,0)),e=pixel(ivec2(0)),f=pixel(ivec2(1,0)),h=pixel(ivec2(0,1));+ if(min(min(b.a,d.a),min(min(e.a,f.a),h.a)) < 0.99999) return e;+ vec3 B=lin(b.rgb),D=lin(d.rgb),E=lin(e.rgb),F=lin(f.rgb),H=lin(h.rgb);+ float mn=min(min(min(D.g,E.g),F.g),min(B.g,H.g));+ float mx=max(max(max(D.g,E.g),F.g),max(B.g,H.g));+ float w=sqrt(clamp(min(mn,1.0-mx)/max(mx,1e-20),0.0,1.0))*{-1.0/(8.0-3.0*sharpness/100.0):.10f};+ vec3 result=clamp((E+w*(B+D+F+H))/(1.0+4.0*w),0.0,1.0);+ return vec4(clamp(enc(mix(E,result,{sharpness/100.0:.8f})),0.0,1.0),e.a);+}}+"""+ elif method == "NVIDIA NIS":+ slider = sharpness / 100.0 - 0.5+ positive = slider >= 0.0+ strength_min = max(0.0, 0.4 + slider * (1.25 if positive else 1.0) * 1.2)+ strength_max = 1.6 + slider * (1.25 if positive else 1.75) * 1.8+ limit_min = max(0.1, 0.14 + slider * (1.25 if positive else 1.0) * 0.32)+ limit_max = 0.5 + slider * (1.25 if positive else 1.0) * 0.6+ source += """float usm(float a,float b,float c,float d,float e,float strength,float limit) {+ float ac=max(max(a,b),c)-min(min(a,b),c),bc=max(max(c,d),e)-min(min(c,d),e);+ float ratio=max(ac,bc)/(min(ac,bc)+1.0/255.0);+ float lti=1.0-clamp((ratio-2.0)/8.0,0.0,1.0);+ return clamp((-0.6001*b+1.2002*c-0.6001*d)*strength,-limit,limit)*lti;+}+vec4 hook() {+ vec4 center=pixel(ivec2(0)); float p[25];+ for(int y=0;y<5;y++) for(int x=0;x<5;x++) {+ vec4 c=pixel(ivec2(x-2,y-2));+ if(c.a<0.99999) return center;+ p[y*5+x]=dot(c.rgb,vec3(0.2126,0.7152,0.0722));+ }+ float g0=abs(p[6]+p[7]+p[8]-p[16]-p[17]-p[18]);+ float g45=abs(p[11]+p[6]+p[7]-p[17]-p[18]-p[13]);+ float g90=abs(p[6]+p[11]+p[16]-p[8]-p[13]-p[18]);+ float g135=abs(p[11]+p[16]+p[17]-p[7]-p[8]-p[13]);+ float ax=max(g0,g90),an=min(g0,g90),dx=max(g45,g135),dn=min(g45,g135);+ bool ad=ax>an*(2.0*1127.0/1024.0)&&ax>64.0/1024.0&&ax>dn;+ bool dd=dx>dn*(2.0*1127.0/1024.0)&&dx>64.0/1024.0&&dx>an;+ float af=ad&&dd?ax/max(ax+dx,1e-20):1.0,df=ad&&dd?dx/max(ax+dx,1e-20):1.0;+"""+ source += f""" float scale=1.0-clamp((p[12]-0.45)/(0.9-0.45),0.0,1.0);+ float strength=scale*{strength_max-strength_min:.10f}+{strength_min:.10f};+ float limit=(scale*{limit_max-limit_min:.10f}+{limit_min:.10f})*p[12];+ float sum=0.0;+ if(ad) sum+=af*(g0>=g90?usm(p[2],p[7],p[12],p[17],p[22],strength,limit):usm(p[10],p[11],p[12],p[13],p[14],strength,limit));+ if(dd) sum+=df*(g45>=g135?usm(p[6],0.5*(p[11]+p[7]),p[12],0.5*(p[17]+p[13]),p[18],strength,limit):usm(p[16],0.5*(p[17]+p[11]),p[12],0.5*(p[13]+p[7]),p[8],strength,limit));+ return vec4(clamp(center.rgb+sum,0.0,1.0),center.a);+}}+"""+ else:+ raise ValueError(f"Unknown sharpening method: {method!r}.")+ return shader_filter(source)+++def sharpen_rgb(pixels: np.ndarray, sharpness: int, *, method: str = "AMD CAS",+ transfer: str = "srgb", alpha: np.ndarray | None = None, controller=None) -> np.ndarray:+ if pixels.ndim != 3 or pixels.shape[2] != 3 or pixels.dtype not in (np.uint8, np.uint16):+ raise ValueError("Sharpening requires uint8/uint16 RGB pixels.")+ if alpha is not None and (alpha.shape != pixels.shape[:2] or alpha.dtype != pixels.dtype):+ raise ValueError("Sharpening alpha must match RGB pixels.")+ graph = sharpening_filter(method, sharpness, transfer, depth=8 if pixels.dtype == np.uint8 else 16)+ if sharpness == 0 or min(pixels.shape[:2]) < 2:+ return pixels.copy()+ rgba = np.empty((*pixels.shape[:2], 4), dtype=pixels.dtype)+ rgba[..., :3] = pixels+ rgba[..., 3] = np.iinfo(pixels.dtype).max if alpha is None else alpha+ result = filter_array(rgba, graph, controller=controller)[..., :3]+ if alpha is not None:+ result[alpha == 0] = pixels[alpha == 0]+ return np.ascontiguousarray(result)diff --git a/src/core/ffmpeg/vulkan.py b/src/core/ffmpeg/vulkan.pynew file mode 100644index 0000000..e8ef85c--- /dev/null+++ b/src/core/ffmpeg/vulkan.py@@ -0,0 +1,587 @@+"""Vendor-neutral Vulkan device selection and FFmpeg command planning.++Codec support is established by actual FFmpeg probes, including an independent+AV1 decode check. CPU mode affects codecs only;+pixel filters use Vulkan on the selected GPU (automatic in CPU mode).+"""+from __future__ import annotations++import ctypes as ct+import json+import os+import re+import subprocess+import tempfile+import uuid+from dataclasses import dataclass+from functools import lru_cache+from pathlib import Path++from .. import app_log+from ..jobs import Cancelled, JobController+from ..paths import FFMPEG, FFPROBE++DEVICE_AUTO = "auto"+DEVICE_CPU = "cpu"+_NO_WINDOW = getattr(subprocess, "CREATE_NO_WINDOW", 0)+++class _ApplicationInfo(ct.Structure):+ _fields_ = [("sType", ct.c_uint32), ("pNext", ct.c_void_p),+ ("name", ct.c_char_p), ("version", ct.c_uint32),+ ("engine", ct.c_char_p), ("engineVersion", ct.c_uint32),+ ("apiVersion", ct.c_uint32)]+++class _InstanceInfo(ct.Structure):+ _fields_ = [("sType", ct.c_uint32), ("pNext", ct.c_void_p),+ ("flags", ct.c_uint32), ("application", ct.POINTER(_ApplicationInfo)),+ ("layerCount", ct.c_uint32), ("layers", ct.c_void_p),+ ("extensionCount", ct.c_uint32), ("extensions", ct.c_void_p)]+++class _Properties(ct.Structure):+ # The public prefix is followed by an aligned, oversized output buffer for+ # VkPhysicalDeviceLimits and VkPhysicalDeviceSparseProperties. Those fields+ # are deliberately not interpreted; this does not guess their ABI layout.+ _fields_ = [("api", ct.c_uint32), ("driver", ct.c_uint32),+ ("vendor", ct.c_uint32), ("device", ct.c_uint32),+ ("kind", ct.c_uint32), ("name", ct.c_char * 256),+ ("pipelineCacheUUID", ct.c_ubyte * 16), ("unused", ct.c_uint64 * 128)]+++class _DeviceID(ct.Structure):+ _fields_ = [("sType", ct.c_uint32), ("pNext", ct.c_void_p),+ ("deviceUUID", ct.c_ubyte * 16), ("driverUUID", ct.c_ubyte * 16),+ ("deviceLUID", ct.c_ubyte * 8), ("nodeMask", ct.c_uint32),+ ("luidValid", ct.c_uint32)]+++class _Properties2(ct.Structure):+ _fields_ = [("sType", ct.c_uint32), ("pNext", ct.c_void_p), ("properties", _Properties)]+++class _Extension(ct.Structure):+ _fields_ = [("name", ct.c_char * 256), ("version", ct.c_uint32)]+++@dataclass(frozen=True)+class VulkanDevice:+ index: int+ uuid: str+ name: str+ device_type: int+ vendor_id: int+ extensions: frozenset[str]++ @property+ def selection(self) -> str:+ return "vulkan:" + self.uuid++ @property+ def discrete(self) -> bool:+ return self.device_type == 2++ @property+ def label(self) -> str:+ kind = "Discrete GPU" if self.discrete else "Integrated GPU" if self.device_type == 1 else "GPU"+ return f"{self.name} ({kind})"+++def valid_selection(value: object) -> bool:+ if not isinstance(value, str):+ return False+ if value in {DEVICE_AUTO, DEVICE_CPU}:+ return True+ if not value.startswith("vulkan:"):+ return False+ try:+ uuid.UUID(value[7:])+ return True+ except (ValueError, AttributeError):+ return False+++def current_selection() -> str:+ # Lazy import avoids the settings -> ffmpeg -> settings import cycle.+ from ...settings.storage import SETTINGS_STATE, load_settings+ from ..paths import CONFIG_PATH+ with SETTINGS_STATE.lock:+ settings = SETTINGS_STATE.current or load_settings(CONFIG_PATH)+ return settings.ffmpeg_device+++@lru_cache(maxsize=1)+def detect_vulkan_devices() -> tuple[VulkanDevice, ...]:+ """Enumerate AMD, Intel and NVIDIA physical devices without CUDA tools."""+ instance = ct.c_void_p()+ try:+ library = ct.WinDLL("vulkan-1.dll") if os.name == "nt" else ct.CDLL("libvulkan.so.1")+ library.vkCreateInstance.argtypes = [ct.POINTER(_InstanceInfo), ct.c_void_p, ct.POINTER(ct.c_void_p)]+ library.vkCreateInstance.restype = ct.c_int32+ library.vkDestroyInstance.argtypes = [ct.c_void_p, ct.c_void_p]+ library.vkEnumeratePhysicalDevices.argtypes = [ct.c_void_p, ct.POINTER(ct.c_uint32), ct.c_void_p]+ library.vkEnumeratePhysicalDevices.restype = ct.c_int32+ library.vkGetPhysicalDeviceProperties2.argtypes = [ct.c_void_p, ct.POINTER(_Properties2)]+ library.vkEnumerateDeviceExtensionProperties.argtypes = [ct.c_void_p, ct.c_char_p, ct.POINTER(ct.c_uint32), ct.c_void_p]+ library.vkEnumerateDeviceExtensionProperties.restype = ct.c_int32+ application = _ApplicationInfo(0, None, b"Visual Enhancer", 1, b"FFmpeg", 1, (1 << 22) | (1 << 12))+ info = _InstanceInfo(1, None, 0, ct.pointer(application), 0, None, 0, None)+ if library.vkCreateInstance(ct.byref(info), None, ct.byref(instance)) != 0:+ return ()+ count = ct.c_uint32()+ if library.vkEnumeratePhysicalDevices(instance, ct.byref(count), None) != 0:+ return ()+ handles = (ct.c_void_p * count.value)()+ if library.vkEnumeratePhysicalDevices(instance, ct.byref(count), handles) not in (0, 5):+ return ()+ devices = []+ for index, handle in enumerate(handles[:count.value]):+ identity = _DeviceID(sType=1000071004)+ properties = _Properties2(sType=1000059001, pNext=ct.addressof(identity))+ library.vkGetPhysicalDeviceProperties2(handle, ct.byref(properties))+ prefix = properties.properties+ if prefix.kind == 4: # Software Vulkan implementations are not GPU acceleration.+ continue+ extension_count = ct.c_uint32()+ library.vkEnumerateDeviceExtensionProperties(handle, None, ct.byref(extension_count), None)+ extensions = (_Extension * extension_count.value)()+ library.vkEnumerateDeviceExtensionProperties(handle, None, ct.byref(extension_count), extensions)+ devices.append(VulkanDevice(+ index, str(uuid.UUID(bytes=bytes(identity.deviceUUID))),+ prefix.name.decode("utf-8", "replace"), int(prefix.kind), int(prefix.vendor),+ frozenset(item.name.decode("ascii", "replace") for item in extensions[:extension_count.value])))+ return tuple(devices)+ except (OSError, AttributeError, ValueError):+ return ()+ finally:+ if instance.value:+ library.vkDestroyInstance(instance, None)+++def device_choices() -> list[dict[str, str]]:+ return [{"label": "Automatic (Best Available)", "value": DEVICE_AUTO},+ {"label": "CPU (Software decoding / encoding)", "value": DEVICE_CPU},+ *[{"label": device.label, "value": device.selection} for device in candidates(DEVICE_AUTO)]]+++def candidates(selection: str | None = None, *, filters: bool = False) -> tuple[VulkanDevice, ...]:+ selection = current_selection() if selection is None else selection+ devices = tuple(sorted(detect_vulkan_devices(), key=lambda device: (not device.discrete, device.index)))+ if selection == DEVICE_CPU:+ return devices if filters else ()+ if selection == DEVICE_AUTO:+ return devices+ selected = tuple(device for device in devices if device.selection == selection)+ if not selected:+ raise ValueError("The selected FFmpeg/Vulkan GPU is unavailable. Choose Automatic or another GPU in Settings.")+ return selected+++def filter_device(selection: str | None = None) -> VulkanDevice:+ devices = candidates(selection, filters=True)+ for device in devices:+ if filter_supported(device.selection):+ return device+ raise RuntimeError("Vulkan GPU filtering is unavailable. Install a current AMD, Intel or NVIDIA Vulkan driver.")+++def device_args(device: VulkanDevice) -> list[str]:+ return ["-init_hw_device", f"vulkan=ve_vk:{device.index}", "-filter_hw_device", "ve_vk"]+++def _capture(command: list[str], timeout: float = 20) -> subprocess.CompletedProcess:+ return subprocess.run(command, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE,+ stderr=subprocess.PIPE, timeout=timeout, creationflags=_NO_WINDOW)+++@lru_cache(maxsize=32)+def filter_supported(selection: str) -> bool:+ device = next((item for item in detect_vulkan_devices() if item.selection == selection), None)+ if device is None:+ return False+ try:+ return _capture([str(FFMPEG), "-v", "error", *device_args(device),+ "-f", "lavfi", "-i", "color=s=64x64:r=1",+ "-vf", "format=rgba,hwupload,libplacebo=format=rgba,hwdownload,format=rgba",+ "-frames:v", "1", "-f", "null", "-"]).returncode == 0+ except (OSError, subprocess.TimeoutExpired):+ return False+++@lru_cache(maxsize=1)+def ffmpeg_encoders() -> frozenset[str]:+ try:+ result = _capture([str(FFMPEG), "-hide_banner", "-encoders"])+ return frozenset(re.findall(r"^\s*V\S{5}\s+(\S+)", result.stdout.decode("utf-8", "replace"), re.M))+ except (OSError, subprocess.TimeoutExpired):+ return frozenset()+++def _probe_av1_bitstream(command: list[str]) -> bool:+ """Reject encoders that initialize successfully but write invalid AV1.++ Some Vulkan driver/FFmpeg combinations produce packets which their own+ hardware decoder accepts, while independent software decoders reject them.+ Check three frames (including references) before selecting that backend.+ The enclosing encoder probe caches this result for each configuration.+ """+ with tempfile.TemporaryDirectory(prefix="visual-enhancer-av1-probe-") as folder:+ sample = Path(folder) / "sample.mkv"+ command = list(command)+ command[command.index("-frames:v") + 1] = "3"+ command[command.index("-f", command.index("-c:v")) + 1] = "matroska"+ command[-1] = str(sample)+ encoded = _capture(command)+ if encoded.returncode or not sample.is_file() or not sample.stat().st_size:+ return False+ # No hardware decoder or command planner here: verify the bitstream+ # independently, rather than repeating the producing backend's behavior.+ decoded = _capture([str(FFMPEG), "-v", "error", "-xerror", "-err_detect", "explode",+ "-i", str(sample), "-map", "0:v:0", "-an", "-sn", "-dn",+ "-fps_mode", "passthrough", "-f", "framemd5", "-"])+ frames = [line for line in decoded.stdout.splitlines() if line.strip() and not line.startswith(b"#")]+ return decoded.returncode == 0 and len(frames) == 3+++@lru_cache(maxsize=128)+def encoder_supported(selection: str, encoder: str, width: int, height: int, pix_fmt: str,+ options: tuple[str, ...] = (), rate: str = "30", time_base: str | None = None) -> bool:+ device = next((item for item in detect_vulkan_devices() if item.selection == selection), None)+ if device is None or encoder not in ffmpeg_encoders():+ return False+ extension = {"h264_vulkan": "VK_KHR_video_encode_h264", "hevc_vulkan": "VK_KHR_video_encode_h265",+ "av1_vulkan": "VK_KHR_video_encode_av1"}.get(encoder)+ if extension and extension not in device.extensions:+ return False+ extras = list(options) or (["-level", "3"] if encoder == "ffv1_vulkan" else ["-profile:v", "3"] if encoder == "prores_ks_vulkan" else ["-qp", "24"])+ probe_matrix = _option(list(options), "-colorspace", "0" if pix_fmt.startswith("gbr") else "bt709")+ try:+ command = [str(FFMPEG), "-v", "error", *device_args(device),+ "-f", "lavfi", "-i", f"{'testsrc2' if encoder == 'av1_vulkan' else 'color'}=s={width}x{height}:r={rate}",+ "-vf", "format=rgba64le,setparams=colorspace=gbr:range=full,hwupload," ++ libplacebo(f"format={pix_fmt}:colorspace={probe_matrix}:range={'pc' if pix_fmt.startswith('gbr') else 'tv'}"), "-frames:v", "1",+ "-c:v", encoder, *extras,+ *(["-enc_time_base:v", time_base] if time_base else []), "-f", "null", "-"]+ supported = _probe_av1_bitstream(command) if encoder == "av1_vulkan" else _capture(command).returncode == 0+ if not supported:+ app_log.info("vulkan", f"{device.name}: {encoder} unavailable for {width}x{height}/{pix_fmt}; trying next codec backend")+ return supported+ except (OSError, subprocess.TimeoutExpired):+ return False+++@lru_cache(maxsize=256)+def _stream_info(source: str, mtime_ns: int, size: int) -> dict:+ result = _capture([str(FFPROBE), "-v", "error", "-select_streams", "v:0",+ "-show_entries", "stream=codec_name,width,height,pix_fmt,avg_frame_rate,r_frame_rate,time_base", "-of", "json", source])+ return json.loads(result.stdout).get("streams", [{}])[0]+++def stream_info(source: str | Path) -> dict:+ path = Path(source)+ stat = path.stat()+ return _stream_info(str(path.resolve()), stat.st_mtime_ns, stat.st_size)+++@lru_cache(maxsize=256)+def _decoder_supported(selection: str, source: str, mtime_ns: int, size: int) -> bool:+ device = next(item for item in detect_vulkan_devices() if item.selection == selection)+ codec = _stream_info(source, mtime_ns, size).get("codec_name")+ extension = {"h264": "VK_KHR_video_decode_h264", "hevc": "VK_KHR_video_decode_h265",+ "av1": "VK_KHR_video_decode_av1", "vp9": "VK_KHR_video_decode_vp9"}.get(codec)+ if extension and extension not in device.extensions:+ return False+ if codec not in {"h264", "hevc", "av1", "vp9", "ffv1", "prores"}:+ return False+ try:+ command = [str(FFMPEG), "-v", "error", *device_args(device),+ "-hwaccel", "vulkan", "-hwaccel_device", "ve_vk", "-hwaccel_output_format", "vulkan",+ "-i", source, "-vf", "format=vulkan,libplacebo=format=rgba,hwdownload,format=rgba",+ "-frames:v", "1", "-f", "null", "-"]+ return _capture(command).returncode == 0+ except (OSError, subprocess.TimeoutExpired):+ return False+++def decoder_args(device: VulkanDevice, source: str | Path, selection: str | None = None) -> list[str]:+ selection = current_selection() if selection is None else selection+ if selection == DEVICE_CPU:+ return []+ if str(source).startswith(("http://", "https://", "rtsp://", "rtmp://")):+ # FFmpeg negotiates the stream's profile with the driver and may fall+ # back to software. hwupload below accepts either resulting layout.+ return ["-hwaccel", "vulkan", "-hwaccel_device", "ve_vk", "-hwaccel_output_format", "vulkan"]+ if not Path(source).is_file():+ return []+ path = Path(source).resolve()+ stat = path.stat()+ if _decoder_supported(device.selection, str(path), stat.st_mtime_ns, stat.st_size):+ return ["-hwaccel", "vulkan", "-hwaccel_device", "ve_vk", "-hwaccel_output_format", "vulkan"]+ return []+++def libplacebo(options: str = "") -> str:+ base = "libplacebo=deband=0:sigmoid=0:disable_linear=1:dithering=-1:apply_filmgrain=0:alpha_mode=premultiplied"+ return base + (":" + options if options else "")+++def quote_filter_path(path: str | Path) -> str:+ # FFmpeg has two escaping levels: the filter graph and the option string.+ value = str(path).replace("\\", "/").replace(":", "\\:").replace("'", "'\\''")+ return "'" + value + "'"+++_VK_ENCODERS = {"libx264": "h264_vulkan", "h264_nvenc": "h264_vulkan",+ "libx265": "hevc_vulkan", "hevc_nvenc": "hevc_vulkan",+ "libsvtav1": "av1_vulkan", "libaom-av1": "av1_vulkan", "av1_nvenc": "av1_vulkan",+ "ffv1": "ffv1_vulkan", "prores_ks": "prores_ks_vulkan"}+_SOFTWARE_ENCODERS = {"h264_nvenc": "libx264", "hevc_nvenc": "libx265", "av1_nvenc": "libsvtav1"}+++def _option(command: list[str], name: str, default=None):+ return command[command.index(name) + 1] if name in command else default+++def _remove_options(command: list[str], names: set[str]) -> list[str]:+ result = []+ index = 0+ while index < len(command):+ if command[index] in names:+ index += 2+ else:+ result.append(command[index])+ index += 1+ return result+++def _split_filters(graph: str) -> list[str]:+ # Commas inside scale expressions or quoted paths are not graph separators.+ parts, start, depth, quoted, escaped = [], 0, 0, False, False+ for index, char in enumerate(graph):+ if escaped:+ escaped = False+ elif char == "\\":+ escaped = True+ elif char == "'":+ quoted = not quoted+ elif not quoted:+ depth += (char == "(") - (char == ")")+ if char == "," and depth == 0:+ parts.append(graph[start:index])+ start = index + 1+ return [part for part in [*parts, graph[start:]] if part]+++def gpu_filter_graph(graph: str) -> str:+ """Replace supported FFmpeg pixel filters with vendor-neutral Vulkan ones."""+ from .filters import scaling_filter+ parts = _split_filters(graph.replace("ve_gpu,", "").replace("ve_gpu", ""))+ result = []+ tone = next((part for part in parts if part.startswith("tonemap=")), None)+ if tone:+ method = re.search(r"tonemap=([^:]+)", tone).group(1)+ result.append(libplacebo(f"color_primaries=bt709:color_trc=bt709:colorspace=bt709:range=tv:tonemapping={method}:format=yuv420p"))+ for part in parts:+ name, _, options = part.partition("=")+ if tone and name in {"tonemap", "zscale", "format"}:+ continue+ if name == "format":+ result.append(libplacebo("format=" + options))+ elif name == "scale":+ if options.startswith("in_range="):+ result.append(libplacebo("range=" + ("pc" if "out_range=pc" in options else "tv")))+ continue+ positional = options.split(":")+ w = positional[0].removeprefix("w=").removeprefix("width=")+ h = positional[1].removeprefix("h=").removeprefix("height=") if len(positional) > 1 else "ih"+ flags = re.search(r"flags=([^:]+)", options)+ method = {"lanczos": "Lanczos", "area": "Area", "bicubic": "Bicubic", "neighbor": "Nearest"}.get(flags.group(1) if flags else "", "Bilinear")+ if w.isdigit() and h.isdigit():+ result.append(scaling_filter(int(w), int(h), method))+ else:+ kernel = {"Lanczos": "lanczos", "Area": "bilinear", "Bicubic": "bicubic", "Nearest": "nearest", "Bilinear": "bilinear"}[method]+ result.append(libplacebo(f"w={w}:h={h}:upscaler={kernel}:downscaler={kernel}"))+ elif name == "zscale":+ values = dict(item.split("=", 1) for item in options.split(":") if "=" in item)+ inputs = {"matrixin": "colorspace", "primariesin": "color_primaries", "transferin": "color_trc", "rangein": "range"}+ assumptions = [f"{inputs[key]}={value}" for key, value in values.items() if key in inputs]+ if assumptions:+ result.append("setparams=" + ":".join(assumptions))+ fields = {"matrix": "colorspace", "m": "colorspace", "primaries": "color_primaries", "p": "color_primaries", "transfer": "color_trc", "t": "color_trc", "range": "range", "r": "range", "w": "w", "h": "h"}+ converted = [f"{fields[key]}={value}" for key, value in values.items() if key in fields and value != "gbr"]+ result.append(libplacebo(":".join(converted)))+ elif name == "transpose":+ direction = "3" if options in {"cclock", "2"} else "1"+ result.append(libplacebo(f"rotate={direction}:w=ih:h=iw"))+ elif name in {"hflip", "vflip"}:+ from .filters import shader_filter+ point = "vec2(1.0-HOOKED_pos.x,HOOKED_pos.y)" if name == "hflip" else "vec2(HOOKED_pos.x,1.0-HOOKED_pos.y)"+ result.append(shader_filter("//!HOOK MAIN\n//!BIND HOOKED\nvec4 hook() { return HOOKED_tex(" + point + "); }\n"))+ elif name == "bwdif":+ result.append(name + "_vulkan" + ("=" + options if options else ""))+ elif name == "lut3d":+ path = options.removeprefix("file=").split(":interp=")[0]+ result.append(libplacebo("lut=" + path + ":lut_type=native"))+ else:+ result.append(part)+ return ",".join(result)+++def prepare_command(command: list[str], *, selection: str | None = None,+ dimensions: tuple[int, int] | None = None, input_format: str | None = None,+ rate: str = "30", time_base: str | None = None) -> list[str]:+ """Choose Vulkan codecs and transfer boundaries for one FFmpeg video output.++ GPU graphs are marked with ve_gpu by their callers. This planner never+ retries a partly written output or silently replaces a requested filter.+ """+ command = list(command)+ if not command or Path(command[0]).name.lower() not in {"ffmpeg", "ffmpeg.exe"}:+ return command+ selection = current_selection() if selection is None else selection+ encoder = _option(command, "-c:v", _option(command, "-vcodec"))+ if encoder == "copy":+ return command+ if encoder is None and "-vf" not in command:+ return command+ graph = _option(command, "-vf", "")+ graph = gpu_filter_graph(graph)+ first_input = _option(command, "-i", "")+ width, height = dimensions or (0, 0)+ if not width and first_input and Path(first_input).is_file():+ metadata = stream_info(first_input)+ input_format = input_format or metadata.get("pix_fmt")+ rate = metadata.get("avg_frame_rate") or metadata.get("r_frame_rate") or rate+ if rate == "0/0":+ rate = "30"+ time_base = metadata.get("time_base") or time_base+ width, height = int(metadata.get("width", 0)), int(metadata.get("height", 0))+ scaled = re.search(r"\bw=(\d+):h=(\d+)", graph)+ if scaled:+ width, height = map(int, scaled.groups())+ capped = re.search(r"w=if\(gt\(iw\\?,(\d+)\)", graph)+ if capped and width > int(capped.group(1)):+ new_width = int(capped.group(1))+ height = max(2, round(height * new_width / width / 2) * 2)+ width = new_width+ pix_fmt = _option(command, "-pix_fmt", "yuv420p")+ target = _VK_ENCODERS.get(encoder)+ vk_format = ("p010le" if "10" in pix_fmt or pix_fmt == "p010le" else "nv12") if target in {"h264_vulkan", "hevc_vulkan", "av1_vulkan"} else pix_fmt+ rgb_output = vk_format.startswith(("gbr", "rgb", "bgr", "argb", "abgr"))+ matrix = _option(command, "-colorspace")+ if rgb_output:+ matrix = "0"+ elif matrix in (None, "2", "0", "gbr", "unknown", "unspecified"):+ matrix = "bt2020nc" if _option(command, "-color_primaries") in {"9", "bt2020"} else "smpte170m" if encoder == "mjpeg" or _option(command, "-f") == "mjpeg" else "bt709"+ if "-colorspace" in command:+ command[command.index("-colorspace")+1] = matrix+ else:+ command[-1:-1] = ["-colorspace", matrix]+ encode_device = None+ codec_options = []+ for name in ("-profile:v", "-profile", "-bits_per_mb", "-level", "-slicecrc", "-b:v"):+ if name in command:+ codec_options += [name, _option(command, name)]+ if target in {"h264_vulkan", "hevc_vulkan", "av1_vulkan"} and (not codec_options or _option(command, "-crf") == "0"):+ codec_options = (["-tune", "lossless"] if _option(command, "-crf") == "0" else []) + ["-rc_mode", "cqp", "-qp", "0" if _option(command, "-crf") == "0" else _option(command, "-crf", "18")]+ for name in ("-color_range", "-colorspace", "-color_primaries", "-color_trc"):+ if name in command:+ codec_options += [name, _option(command, name)]+ if _option(command, "-enc_time_base", _option(command, "-enc_time_base:v")) not in (None, "demux", "filter"):+ time_base = _option(command, "-enc_time_base", _option(command, "-enc_time_base:v"))+ if target and width > 0 and height > 0:+ encode_device = next((device for device in candidates(selection)+ if encoder_supported(device.selection, target, width, height, vk_format, tuple(codec_options), rate, time_base)), None)+ device = encode_device or filter_device(selection)+ decode = decoder_args(device, first_input, selection) if first_input else []+ command = _remove_options(command, {"-init_hw_device", "-filter_hw_device", "-hwaccel", "-hwaccel_device", "-hwaccel_output_format"})+ input_index = command.index("-i")+ command[input_index:input_index] = decode+ command[1:1] = device_args(device)+ graph = "hwupload" + ("," + graph if graph else "")+ def output_format(fmt: str) -> str:+ rgb = fmt.startswith(("gbr", "rgb", "bgr", "argb", "abgr"))+ color_options = ["format=" + fmt]+ explicit_range = _option(command, "-color_range")+ color_options.append("range=" + (explicit_range if explicit_range not in (None, "0", "unknown", "unspecified") else "pc" if rgb else "tv"))+ for name, option in (("-color_primaries", "color_primaries"), ("-color_trc", "color_trc"), ("-colorspace", "colorspace")):+ value = _option(command, name)+ if value not in (None, "unknown", "unspecified", "2"):+ color_options.append(f"{option}={value}")+ result = libplacebo(":".join(color_options))+ narrow_rgb = re.fullmatch(r"(gbrap|gbrp)(?:9|10|12|14)(le|be)", fmt)+ if narrow_rgb:+ # Sub-16-bit RGB uses 16-bit storage with a smaller legal range.+ # YUV superwhites / conversion overshoot can survive direct output+ # as codes above that range; packed RGBA64 conversion then wraps+ # the bright channels to black. A full-range UNORM16 surface clamps+ # in the output transfer function before the lower-depth packing.+ normalized = ["format=" + narrow_rgb[1] + "16" + narrow_rgb[2], *color_options[1:]]+ return libplacebo(":".join(normalized)) + "," + result+ return result+ if encode_device:+ if input_format != vk_format or _option(command, "-vf"):+ graph = (graph + "," if graph else "") + output_format(vk_format)+ lossless = _option(command, "-crf") == "0" or _option(command, "-cq") == "0"+ quality = _option(command, "-crf", _option(command, "-cq", "18"))+ command = _remove_options(command, {"-preset", "-tune", "-crf", "-cq", "-rc", "-gpu",+ "-x264-params", "-x265-params", "-cpu-used", "-pix_fmt"})+ flag = "-c:v" if "-c:v" in command else "-vcodec"+ command[command.index(flag) + 1] = target+ if target in {"h264_vulkan", "hevc_vulkan", "av1_vulkan"}:+ if lossless:+ command = _remove_options(command, {"-b:v", "-q:v"})+ command[-1:-1] = ["-tune", "lossless", "-rc_mode", "cqp", "-qp", "0"]+ elif "-b:v" not in command or _option(command, "-b:v") == "0":+ command = _remove_options(command, {"-b:v"})+ command[-1:-1] = ["-rc_mode", "cqp", "-qp", quality]+ else:+ graph = (graph + "," if graph else "") + f"{output_format(pix_fmt)},hwdownload,format={pix_fmt}"+ if encoder in _SOFTWARE_ENCODERS:+ command[command.index("-c:v") + 1] = _SOFTWARE_ENCODERS[encoder]+ command = _remove_options(command, {"-gpu", "-tune", "-rc", "-cq", "-preset"})+ if "-vf" in command:+ command[command.index("-vf") + 1] = graph+ else:+ command[-1:-1] = ["-vf", graph]+ app_log.info("vulkan", f"filters={device.name} decode={'Vulkan' if decode else 'CPU'} encode={target if encode_device else encoder}")+ return command+++def run(command: list[str], controller: JobController, label: str, *, cwd: Path | None = None,+ selection: str | None = None, dimensions: tuple[int, int] | None = None,+ progress=None, metadata: dict | None = None) -> None:+ if controller.cancel.is_set():+ raise Cancelled("Render stopped by user.")+ command = prepare_command(command, selection=selection or getattr(controller, "ffmpeg_device", None), dimensions=dimensions)+ if progress is not None:+ from .progress import run_with_progress+ return run_with_progress(command, controller, label, progress, metadata=metadata, cwd=cwd)+ process = subprocess.Popen(command, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE,+ cwd=cwd, creationflags=_NO_WINDOW)+ controller.register(process)+ try:+ while True:+ if controller.cancel.is_set():+ raise Cancelled("Render stopped by user.")+ try:+ _, errors = process.communicate(timeout=0.2)+ break+ except subprocess.TimeoutExpired:+ continue+ if process.returncode:+ raise RuntimeError(f"{label} failed: {errors.decode('utf-8', 'replace')[-2500:]}")+ finally:+ if process.poll() is None:+ process.kill()+ process.wait(timeout=5)+ controller.unregister(process)+ if process.stderr:+ process.stderr.close()+++def clear_caches() -> None:+ for function in (detect_vulkan_devices, filter_supported, ffmpeg_encoders,+ encoder_supported, _stream_info, _decoder_supported):+ function.cache_clear()diff --git a/src/core/jobs.py b/src/core/jobs.pyindex 2f95c7c..0722931 100644--- a/src/core/jobs.py+++ b/src/core/jobs.py@@ -17,6 +17,7 @@ class JobController:def __init__(self) -> None:self.cancel = threading.Event()+ self.ffmpeg_device: str | None = Noneself._lock = threading.Lock()self._processes: list[subprocess.Popen] = []diff --git a/src/core/neural_bridge.py b/src/core/neural_bridge.pyindex 60c3c27..0573f13 100644--- a/src/core/neural_bridge.py+++ b/src/core/neural_bridge.py@@ -295,14 +295,6 @@ def _text(value: bytes | None) -> str:return value.decode("utf-8", "replace") if value else ""-def _json_line(event: str, **values: Any) -> str:- return json.dumps(- {"event": event, "monotonic_seconds": time.monotonic(), **values},- sort_keys=True,- separators=(",", ":"),- )--class _CudaDriver:"""Small CUDA Driver API wrapper; no CUDA toolkit or Python add-on needed."""diff --git a/src/core/paths.py b/src/core/paths.pyindex 5c0b9f4..2277b63 100644--- a/src/core/paths.py+++ b/src/core/paths.py@@ -1,10 +1,8 @@from __future__ import annotations-from pathlib import Path+from ..portable import ROOT, TEMP, UI_SETTINGS_PATH-ROOT = Path(__file__).resolve().parents[2]-TEMP = ROOT / "temp"APP_TEMP = TEMP / "app"PREVIEW_CACHE = APP_TEMP / "cache"RUNTIME = ROOT / "bin" / "runtime"diff --git a/src/core/rolling_cache.py b/src/core/rolling_cache.pynew file mode 100644index 0000000..fc6117c--- /dev/null+++ b/src/core/rolling_cache.py@@ -0,0 +1,284 @@+"""Bounded FFV1 or ProRes Proxy packet spool with continuous codec state.++Packets become readable after their bytes are written, without waiting for a+whole segment. Segments are unlinked only when sealed and fully consumed.+Timestamps are carried separately, avoiding container timestamp rounding at+cache boundaries. This is disposable working storage, not a restart checkpoint.+"""+from __future__ import annotations++import threading+from collections import deque+from dataclasses import dataclass+from pathlib import Path++import av+from av.video.reformatter import ColorRange, Colorspace, VideoReformatter++from .jobs import Cancelled+from .cache_video import CACHE_VIDEO_CODECS+++CACHE_BYTES = 5_000_000_000+SEGMENT_BYTES = 64 * 1024 * 1024+++@dataclass+class _Segment:+ path: Path+ size: int = 0+ readers: int = 0+ sealed: bool = False+++@dataclass+class _Packet:+ segment: _Segment+ offset: int+ size: int+ pts: int+ duration: int+ time_base: object+++class RollingFrameCache:+ def __init__(self, frames, directory: Path, controller, *,+ limit: int = CACHE_BYTES, segment_bytes: int = SEGMENT_BYTES,+ max_frames: int = 1800, threads: int = 4, codec: str = "FFV1"):+ if limit < 1 or max_frames < 1:+ raise ValueError("Rolling cache limits must be positive.")+ if codec not in CACHE_VIDEO_CODECS:+ raise ValueError(f"Unknown rolling cache codec: {codec!r}.")+ self.frames, self.directory, self.controller = iter(frames), Path(directory), controller+ self.codec = codec+ self.limit = int(limit)+ self.segment_bytes = min(int(segment_bytes), max(1, self.limit // 4))+ self.max_frames, self.threads = int(max_frames), int(threads)+ self.condition = threading.Condition()+ self.packets = deque()+ self.segments: list[_Segment] = []+ self.stop = threading.Event()+ self.finished = False+ self.failure = None+ self.codec_info = None+ self.cache_colorspace = None+ self.used_bytes = self.peak_bytes = self.written_frames = self.read_frames = 0+ self.waits = 0+ self.thread = None+ self.directory.mkdir(parents=True, exist_ok=True)++ def _check(self):+ if self.failure is not None:+ raise self.failure+ if self.stop.is_set() or self.controller.cancel.is_set():+ raise Cancelled("Rolling cache stopped.")++ def _reclaim(self, segment):+ # Called with the condition held; there are no open reader handles.+ if segment.sealed and segment.readers == 0:+ segment.path.unlink(missing_ok=True)+ self.used_bytes -= segment.size+ self.segments.remove(segment)+ self.condition.notify_all()++ def _produce(self):+ codec = file = segment = None+ reformatter = VideoReformatter()+ sequence = 0++ def seal():+ nonlocal file, segment+ if file is not None:+ file.close()+ file = None+ with self.condition:+ segment.sealed = True+ self._reclaim(segment)+ segment = None++ try:+ for frame in self.frames:+ self._check()+ if codec is None:+ fmt = frame.format.name+ if self.codec == "FFV1":+ supported = {f.name for f in av.Codec("ffv1", "w").video_formats}+ if fmt == "rgba":+ fmt = "bgra" # Exact channel permutation, no YUV conversion.+ if fmt not in supported:+ raise ValueError(f"FFV1 rolling cache cannot preserve {fmt} samples.")+ codec = av.CodecContext.create("ffv1", "w")+ else:+ fmt = "yuv422p10le"+ codec = av.CodecContext.create("prores_ks", "w")+ matrix = int(frame.colorspace)+ primaries = int(frame.color_primaries)+ self.cache_colorspace = (+ Colorspace.BT2020 if 9 in (matrix, primaries) else+ Colorspace.ITU601 if matrix in {5, 6} or primaries in {5, 6} else+ Colorspace.ITU709+ )+ codec.width, codec.height, codec.pix_fmt = frame.width, frame.height, fmt+ codec.time_base = frame.time_base+ codec.thread_count = self.threads+ if self.codec == "FFV1":+ codec.thread_type = "SLICE"+ codec.options = {"level": "3", "slicecrc": "1", "coder": "1", "context": "0"}+ else:+ codec.options = {"profile": "0"}+ codec.gop_size = 1+ codec.open()+ self.codec_info = (bytes(codec.extradata or b""), frame.width, frame.height,+ frame.colorspace, frame.color_range,+ frame.color_primaries, frame.color_trc)+ if (frame.width, frame.height) != (codec.width, codec.height):+ raise ValueError("Frame dimensions changed within the rolling cache.")+ if self.codec == "FFV1":+ pixels = frame if frame.format.name == codec.pix_fmt else frame.reformat(format=codec.pix_fmt)+ else:+ pixels = reformatter.reformat(frame, format=codec.pix_fmt,+ dst_colorspace=self.cache_colorspace,+ src_color_range=ColorRange.JPEG if frame.format.is_rgb else ColorRange.MPEG,+ dst_color_range=ColorRange.MPEG)+ packets = codec.encode(pixels)+ if len(packets) != 1:+ raise RuntimeError(f"{self.codec} cache did not encode exactly one packet per frame.")+ data = bytes(packets[0])+ size = len(data)+ if size > self.limit:+ raise RuntimeError("A single cached frame exceeds the rolling cache capacity.")+ if segment is not None and segment.size + size > self.segment_bytes:+ seal()+ with self.condition:+ full = self.used_bytes + size > self.limit or len(self.packets) >= self.max_frames+ if full:+ # Sealing releases an already-consumed current segment and+ # prevents deadlock even with a cache smaller than one chunk.+ seal()+ with self.condition:+ while self.used_bytes + size > self.limit or len(self.packets) >= self.max_frames:+ self._check()+ self.waits += 1+ self.condition.wait(.1)+ self._check()+ if file is None:+ suffix = ".ffv1" if self.codec == "FFV1" else ".prores"+ segment = _Segment(self.directory / f"{sequence:08d}{suffix}")+ sequence += 1+ file = segment.path.open("wb", buffering=0)+ self.segments.append(segment)+ offset = segment.size+ self.used_bytes += size+ self.peak_bytes = max(self.peak_bytes, self.used_bytes)+ segment.size += size+ segment.readers += 1+ remaining = memoryview(data)+ while remaining:+ self._check()+ written = file.write(remaining)+ if not written:+ raise OSError("Rolling cache write did not complete.")+ remaining = remaining[written:]+ del remaining+ with self.condition:+ self.packets.append(_Packet(segment, offset, size, frame.pts,+ frame.duration, frame.time_base))+ self.written_frames += 1+ self.condition.notify_all()+ del frame, pixels, packets, data+ if codec is not None and codec.encode():+ raise RuntimeError(f"{self.codec} cache unexpectedly delayed video packets.")+ except BaseException as exc:+ with self.condition:+ self.failure = exc+ self.condition.notify_all()+ finally:+ # A final flush/close/unlink error must wake the consumer too. If+ # cleanup throws before finished is set, an empty consumer queue+ # would otherwise wait forever for a producer that has exited.+ for cleanup in (seal, getattr(self.frames, "close", None)):+ if cleanup:+ try:+ cleanup()+ except BaseException as exc:+ with self.condition:+ if self.failure is None:+ self.failure = exc+ with self.condition:+ self.finished = True+ self.condition.notify_all()++ def __iter__(self):+ if self.thread is not None:+ raise RuntimeError("A rolling cache can only be consumed once.")+ self.thread = threading.Thread(target=self._produce, name="rolling-frame-cache", daemon=True)+ self.thread.start()+ decoder = None+ reformatter = VideoReformatter()+ try:+ while True:+ with self.condition:+ while not self.packets and not self.finished:+ self._check()+ self.condition.wait(.1)+ self._check()+ if not self.packets:+ break+ record = self.packets.popleft()+ self.condition.notify_all()+ if decoder is None:+ extra, width, height, *_ = self.codec_info+ decoder = av.CodecContext.create("ffv1" if self.codec == "FFV1" else "prores", "r")+ decoder.extradata = extra+ decoder.width, decoder.height = width, height+ decoder.thread_count = self.threads+ decoder.thread_type = "SLICE"+ decoder.open()+ with record.segment.path.open("rb", buffering=0) as source:+ source.seek(record.offset)+ data = source.read(record.size)+ if len(data) != record.size:+ raise RuntimeError("Rolling cache packet is incomplete.")+ decoded = decoder.decode(av.Packet(data))+ if len(decoded) != 1 or decoded[0].is_corrupt:+ raise RuntimeError("Rolling cache failed to decode a complete frame.")+ frame = decoded[0]+ if self.codec == "ProRes Proxy":+ # Downstream rolling stages keep an RGB10 state. Convert+ # the decoded 4:2:2 frame back to that working format.+ frame = reformatter.reformat(frame, format="gbrp10le",+ src_colorspace=self.cache_colorspace,+ src_color_range=ColorRange.MPEG,+ dst_color_range=ColorRange.JPEG)+ frame.pts, frame.duration, frame.time_base = record.pts, record.duration, record.time_base+ (_, _, _, frame.colorspace, frame.color_range,+ frame.color_primaries, frame.color_trc) = self.codec_info+ with self.condition:+ record.segment.readers -= 1+ self._reclaim(record.segment)+ self.read_frames += 1+ del data, record, decoded+ yield frame+ if self.read_frames != self.written_frames:+ raise RuntimeError("Rolling cache frame accounting does not match.")+ finally:+ self.close()++ def close(self):+ self.stop.set()+ with self.condition:+ self.condition.notify_all()+ if self.thread is not None and self.thread is not threading.current_thread():+ self.thread.join(timeout=30)+ if self.thread.is_alive():+ raise RuntimeError("Rolling cache producer did not stop.")+ with self.condition:+ for segment in list(self.segments):+ segment.path.unlink(missing_ok=True)+ self.segments.clear()+ self.packets.clear()+ self.used_bytes = 0+++# Keep the previous import available to callers outside the desktop workflow.+LosslessFrameCache = RollingFrameCachediff --git a/src/core/runtime.py b/src/core/runtime.pyindex e0eef03..2beaa32 100644--- a/src/core/runtime.py+++ b/src/core/runtime.py@@ -1,1119 +1,1100 @@-from __future__ import annotations--import json-import contextlib-import math-import mmap-import os-import re-import subprocess-import threading-import time-from dataclasses import dataclass, field-from pathlib import Path-from typing import Any--import cv2-import numpy as np--from .gpu_detection import detect_gpus-from .gpu_memory import GPUVramTracker-from .gpu_selection import resolve_runtime_ai_gpu-from .jobs import Cancelled, JobController-from .neural_bridge import (- BRIDGE_ABI_VERSION,- BRIDGE_MANAGER,- BridgeSessionDiagnostics,- CudaFrameBuffers,- CudaMaskBuffer,- FORMAT_NV12,- FORMAT_P010,-)-from .nr_composition import mask_report, mask_selection, prepare_nr_mask-from .paths import (- DLSSNR_BRIDGE,- DLSSNR_CALLER_SHIM,- DLSSNR_DIR,- DLSSG_DIR,- FFMPEG,- FFPROBE,- NEURAL_RUNTIME,- RUNTIME,-)---NR_STYLES = {- "Default": 0,- "Natural": 1,- "Cinematic": 2,-}--# Feature 18 is evaluated at the final neural dimensions. Scaling below 1x is-# 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},-}-UPSCALING_CHOICES = tuple(- (mode["label"], factor) for factor, mode in UPSCALING_MODES.items()-)---def resolve_upscaling_mode(raw_factor: float) -> tuple[float, dict[str, str | int]]:- try:- factor = float(raw_factor)- except (TypeError, ValueError) as exc:- raise ValueError("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, 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, 200%, 175%, 150%, 125%, 75%, 50%, 25%.")---def _nearest_even(value: float) -> int:- return max(2, int(math.floor(value / 2.0 + 0.5)) * 2)---def resolve_output_size(width: int, height: int, factor: float) -> tuple[int, int]:- factor, _ = resolve_upscaling_mode(factor)- output_width = _nearest_even(int(width) * factor)- output_height = _nearest_even(int(height) * factor)- if min(output_width, output_height) < 64:- raise ValueError(- f"The requested {output_width}×{output_height} output is below the supported "- f"64×64 minimum. Choose Source, 75%, or 50% for this input."- )- return output_width, output_height---def resolve_native_settings(options: Any) -> dict[str, int | float | bool]:- try:- style = NR_STYLES[options.nr_style]- except KeyError as exc:- raise ValueError(- f"Unknown NR Style: {options.nr_style!r}. Choose one of: {', '.join(NR_STYLES)}."- ) from exc-- controls = {- "NR Intensity": (options.nr_intensity, 0.0, 2.0),- "Local Tone Strength": (options.local_tone_strength, 0.0, 2.0),- "Local Structure Strength": (options.local_structure_strength, 0.0, 2.0),- "Skin Structure Strength": (options.skin_structure_strength, -1.0, 2.0),- "NR Color Strength": (options.nr_color_strength, 0.0, 1.0),- "Tone Preservation": (options.tone_preservation, 0.0, 1.0),- "Face/Skin Protection": (options.face_skin_protection, 0.0, 1.0),- "Grain Preservation": (options.grain_preservation, 0.0, 1.0),- "Shimmer Suppression": (getattr(options, "shimmer_suppression", 0.0), 0.0, 1.0),- }- validated: dict[str, float] = {}- for label, (raw_value, minimum, maximum) in controls.items():- try:- value = float(raw_value)- except (TypeError, ValueError) as exc:- raise ValueError(- f"{label} must be a number between {minimum:g} and {maximum:g}."- ) from exc- if not math.isfinite(value) or not minimum <= value <= maximum:- raise ValueError(f"{label} must be between {minimum:g} and {maximum:g}.")- validated[label] = value-- if not isinstance(options.automatic_mask, bool):- raise ValueError("Automatic Mask must be a boolean value.")- mask_feather = getattr(options, "mask_feather", 0)- if isinstance(mask_feather, bool) or int(mask_feather) != mask_feather:- 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.")- codec_name = str(getattr(options, "codec", ""))- nr_passes = getattr(options, "nr_passes", 1)- if isinstance(nr_passes, bool) or not isinstance(nr_passes, int):- raise ValueError("NR Passes must be an integer from 1 to 4.")- if not 1 <= nr_passes <= 4:- raise ValueError("NR Passes must be between 1 and 4.")-- # NVOF remains available for adapter/driver validation. On the tested- # RTX 4060 Ti / 617.14 it was slower and had a higher warped-residual- # error than the bundled Lucas-Kanade path, so it is not a default.- # Frame-boundary NVENC also retains its native NVOF stall guard.- prefer_nvof = bool(- codec_name and "NVENC" not in codec_name.upper()- and os.environ.get("DLSS5NR_EXPERIMENTAL_NVOF") == "1"- )- return {- "profile": 0,- "style": style,- "auto_mask": int(options.automatic_mask),- "intensity": validated["NR Intensity"],- "nr_passes": nr_passes,- "local_tone": validated["Local Tone Strength"],- "local_structure": validated["Local Structure Strength"],- "skin_structure": validated["Skin Structure Strength"],- "color_strength": validated["NR Color Strength"],- "tone_preservation": validated["Tone Preservation"],- "face_skin_protection": validated["Face/Skin Protection"],- "grain_preservation": validated["Grain Preservation"],- "shimmer_suppression": validated["Shimmer Suppression"],- "prefer_nvof": prefer_nvof,- "mask_feather": int(mask_feather),- "gpu_mode": True,- }---def inspect_runtime_bundle(- bridge_path: Path | None = None,- neural_path: Path | None = None,-) -> dict[str, Any]:- bridge = bridge_path or DLSSNR_BRIDGE- neural = neural_path or NEURAL_RUNTIME- return {- "bridge": {- "path": str(bridge.resolve()),- "version": BRIDGE_MANAGER.version,- "abi_version": BRIDGE_ABI_VERSION,- "release": "D3D12/NGX CUDA bridge",- },- "caller_shim": {"path": str(DLSSNR_CALLER_SHIM.resolve())},- "neural_runtime": {- "path": str(neural.resolve()),- "version": "driver-compatible",- "release": "NVIDIA DLSS Neural Rendering runtime",- },- }---def validate_gpu_runtime(- gpu: dict[str, Any], bundle: dict[str, Any] | None = None-) -> dict[str, Any]:- del gpu- return bundle or inspect_runtime_bundle()---def write_failure_report(- *,- operation: str,- source: str,- error: BaseException | str,- gpu: dict[str, Any] | None,- runtime_bundle: dict[str, Any] | None,- bridge_status: dict[str, Any] | None = None,- bridge_log: list[str] | None = None,- logs_dir: Path | None = None,- diagnostics: dict[str, Any] | None = None,-) -> Path:- """Persist a compact ``.err`` failure file and log one line."""- from . import app_log-- safe_operation = re.sub(r"[^A-Za-z0-9_.-]+", "-", operation).strip("-") or "render"- stamp = time.strftime("%Y%m%d-%H%M%S") + f"-{time.time_ns() % 1_000_000:06d}"- gpu_name = ""- try:- gpu_name = str((gpu or {}).get("display_name") or (gpu or {}).get("name") or "")- except Exception:- gpu_name = ""- tails: dict[str, object] = {}- if bridge_log:- tails["bridge"] = list(bridge_log)[-40:]- if diagnostics:- tails["diagnostics"] = str(diagnostics)[-4000:]- return app_log.fail(- safe_operation,- f"{safe_operation}-failure-{stamp}",- f"{error} | src={Path(source).name} {gpu_name}".strip(),- tails or None,- )--+from __future__ import annotations++import json+import contextlib+import math+import mmap+import os+import re+import subprocess+import threading+import time+from dataclasses import dataclass, field+from pathlib import Path+from typing import Any++import cv2+import numpy as np++from .gpu_detection import detect_gpus+from .gpu_memory import GPUVramTracker+from .gpu_selection import resolve_runtime_ai_gpu+from .jobs import Cancelled, JobController+from .neural_bridge import (+ BRIDGE_ABI_VERSION,+ BRIDGE_MANAGER,+ BridgeSessionDiagnostics,+ CudaFrameBuffers,+ CudaMaskBuffer,+ FORMAT_NV12,+ FORMAT_P010,+)+from .nr_composition import mask_report, mask_selection, prepare_nr_mask+from .paths import (+ DLSSNR_BRIDGE,+ DLSSNR_CALLER_SHIM,+ DLSSNR_DIR,+ DLSSG_DIR,+ FFMPEG,+ FFPROBE,+ NEURAL_RUNTIME,+ RUNTIME,+)+++NR_STYLES = {+ "Default": 0,+ "Natural": 1,+ "Cinematic": 2,+}++# Feature 18 is evaluated at the final neural dimensions. Scaling below 1x is+# 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},+}+UPSCALING_CHOICES = tuple(+ (mode["label"], factor) for factor, mode in UPSCALING_MODES.items()+)+++def resolve_upscaling_mode(raw_factor: float) -> tuple[float, dict[str, str | int]]:+ try:+ factor = float(raw_factor)+ except (TypeError, ValueError) as exc:+ raise ValueError("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, 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, 200%, 175%, 150%, 125%, 75%, 50%, 25%.")+++def _nearest_even(value: float) -> int:+ return max(2, int(math.floor(value / 2.0 + 0.5)) * 2)+++def resolve_output_size(width: int, height: int, factor: float) -> tuple[int, int]:+ factor, _ = resolve_upscaling_mode(factor)+ output_width = _nearest_even(int(width) * factor)+ output_height = _nearest_even(int(height) * factor)+ if min(output_width, output_height) < 64:+ raise ValueError(+ f"The requested {output_width}×{output_height} output is below the supported "+ f"64×64 minimum. Choose Source, 75%, or 50% for this input."+ )+ return output_width, output_height+++def resolve_native_settings(options: Any) -> dict[str, int | float | bool]:+ try:+ style = NR_STYLES[options.nr_style]+ except KeyError as exc:+ raise ValueError(+ f"Unknown NR Style: {options.nr_style!r}. Choose one of: {', '.join(NR_STYLES)}."+ ) from exc++ controls = {+ "NR Intensity": (options.nr_intensity, 0.0, 2.0),+ "Local Tone Strength": (options.local_tone_strength, 0.0, 2.0),+ "Local Structure Strength": (options.local_structure_strength, 0.0, 2.0),+ "Skin Structure Strength": (options.skin_structure_strength, -1.0, 2.0),+ "NR Color Strength": (options.nr_color_strength, 0.0, 1.0),+ "Tone Preservation": (options.tone_preservation, 0.0, 1.0),+ "Face/Skin Protection": (options.face_skin_protection, 0.0, 1.0),+ "Grain Preservation": (options.grain_preservation, 0.0, 1.0),+ "Shimmer Suppression": (getattr(options, "shimmer_suppression", 0.0), 0.0, 1.0),+ }+ validated: dict[str, float] = {}+ for label, (raw_value, minimum, maximum) in controls.items():+ try:+ value = float(raw_value)+ except (TypeError, ValueError) as exc:+ raise ValueError(+ f"{label} must be a number between {minimum:g} and {maximum:g}."+ ) from exc+ if not math.isfinite(value) or not minimum <= value <= maximum:+ raise ValueError(f"{label} must be between {minimum:g} and {maximum:g}.")+ validated[label] = value++ if not isinstance(options.automatic_mask, bool):+ raise ValueError("Automatic Mask must be a boolean value.")+ mask_feather = getattr(options, "mask_feather", 0)+ if isinstance(mask_feather, bool) or int(mask_feather) != mask_feather:+ 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.")+ codec_name = str(getattr(options, "codec", ""))+ nr_passes = getattr(options, "nr_passes", 1)+ if isinstance(nr_passes, bool) or not isinstance(nr_passes, int):+ raise ValueError("NR Passes must be an integer from 1 to 4.")+ if not 1 <= nr_passes <= 4:+ raise ValueError("NR Passes must be between 1 and 4.")++ # NVOF remains available for adapter/driver validation. On the tested+ # RTX 4060 Ti / 617.14 it was slower and had a higher warped-residual+ # error than the bundled Lucas-Kanade path, so it is not a default.+ # Frame-boundary NVENC also retains its native NVOF stall guard.+ prefer_nvof = bool(+ codec_name and "NVENC" not in codec_name.upper()+ and os.environ.get("DLSS5NR_EXPERIMENTAL_NVOF") == "1"+ )+ return {+ "profile": 0,+ "style": style,+ "auto_mask": int(options.automatic_mask),+ "intensity": validated["NR Intensity"],+ "nr_passes": nr_passes,+ "local_tone": validated["Local Tone Strength"],+ "local_structure": validated["Local Structure Strength"],+ "skin_structure": validated["Skin Structure Strength"],+ "color_strength": validated["NR Color Strength"],+ "tone_preservation": validated["Tone Preservation"],+ "face_skin_protection": validated["Face/Skin Protection"],+ "grain_preservation": validated["Grain Preservation"],+ "shimmer_suppression": validated["Shimmer Suppression"],+ "prefer_nvof": prefer_nvof,+ "mask_feather": int(mask_feather),+ "gpu_mode": True,+ }+++def inspect_runtime_bundle(+ bridge_path: Path | None = None,+ neural_path: Path | None = None,+) -> dict[str, Any]:+ bridge = bridge_path or DLSSNR_BRIDGE+ neural = neural_path or NEURAL_RUNTIME+ return {+ "bridge": {+ "path": str(bridge.resolve()),+ "version": BRIDGE_MANAGER.version,+ "abi_version": BRIDGE_ABI_VERSION,+ "release": "D3D12/NGX CUDA bridge",+ },+ "caller_shim": {"path": str(DLSSNR_CALLER_SHIM.resolve())},+ "neural_runtime": {+ "path": str(neural.resolve()),+ "version": "driver-compatible",+ "release": "NVIDIA DLSS Neural Rendering runtime",+ },+ }+++def validate_gpu_runtime(+ gpu: dict[str, Any], bundle: dict[str, Any] | None = None+) -> dict[str, Any]:+ del gpu+ return bundle or inspect_runtime_bundle()+++def write_failure_report(+ *,+ operation: str,+ source: str,+ error: BaseException | str,+ gpu: dict[str, Any] | None,+ runtime_bundle: dict[str, Any] | None,+ bridge_status: dict[str, Any] | None = None,+ bridge_log: list[str] | None = None,+ logs_dir: Path | None = None,+ diagnostics: dict[str, Any] | None = None,+) -> Path:+ """Persist a compact ``.err`` failure file and log one line."""+ from . import app_log++ safe_operation = re.sub(r"[^A-Za-z0-9_.-]+", "-", operation).strip("-") or "render"+ stamp = time.strftime("%Y%m%d-%H%M%S") + f"-{time.time_ns() % 1_000_000:06d}"+ gpu_name = ""+ try:+ gpu_name = str((gpu or {}).get("display_name") or (gpu or {}).get("name") or "")+ except Exception:+ gpu_name = ""+ tails: dict[str, object] = {}+ if bridge_log:+ tails["bridge"] = list(bridge_log)[-40:]+ if diagnostics:+ tails["diagnostics"] = str(diagnostics)[-4000:]+ return app_log.fail(+ safe_operation,+ f"{safe_operation}-failure-{stamp}",+ f"{error} | src={Path(source).name} {gpu_name}".strip(),+ tails or None,+ )++def resize_fit(rgba: np.ndarray, width: int, height: int, *,- interpolation: str = "Lanczos4") -> np.ndarray:- source_height, source_width = rgba.shape[:2]- if source_width == width and source_height == height:- return np.ascontiguousarray(rgba)- scale = min(width / source_width, height / source_height)- fit_width = max(1, min(width, int(round(source_width * scale))))- fit_height = max(1, min(height, int(round(source_height * scale))))- methods = {- "Lanczos4": cv2.INTER_LANCZOS4,- "Area": cv2.INTER_AREA,- "Bicubic": cv2.INTER_CUBIC,- "Bilinear": cv2.INTER_LINEAR,- "Nearest": cv2.INTER_NEAREST,- }- if interpolation not in methods:- raise ValueError(f"Unknown image scaling filter: {interpolation!r}.")- resized = cv2.resize(rgba, (fit_width, fit_height), interpolation=methods[interpolation])- canvas = np.zeros((height, width, 4), dtype=rgba.dtype)- canvas[..., 3] = np.iinfo(rgba.dtype).max- x = (width - fit_width) // 2- y = (height - fit_height) // 2- canvas[y : y + fit_height, x : x + fit_width] = resized- return canvas---def rotate_frame(frame: np.ndarray, rotation: int) -> np.ndarray:- if rotation == 90:- return np.ascontiguousarray(np.rot90(frame, 3))- if rotation == 180:- return np.ascontiguousarray(np.rot90(frame, 2))- if rotation == 270:- return np.ascontiguousarray(np.rot90(frame, 1))- return frame---def validate_runtime_files() -> None:- required = [FFMPEG, FFPROBE, DLSSNR_BRIDGE, DLSSNR_CALLER_SHIM, NEURAL_RUNTIME]- missing = [str(path) for path in required if not path.is_file()]- if missing:- raise RuntimeError(- "The Neural Rendering runtime is incomplete:\n" + "\n".join(missing)- )---class DLSSFrameSession:- """Virtual feature-18 render session running on the shared system bridge."""-- def __init__(- self,- *,- input_width: int,- input_height: int,- output_width: int,- output_height: int,- frame_count: int | None,- warmup_frames: int,- factor: float,- mode: dict[str, str | int],- native_settings: dict[str, int | float | bool],- gpu: dict[str, Any],- runtime_bundle: dict[str, Any],- controller: JobController,- cuda_video: bool = False,- composition_mask: object | None = None,- ) -> None:- del input_width, input_height, warmup_frames- if frame_count is not None and (- isinstance(frame_count, bool)- or not isinstance(frame_count, int)- or not 0 < frame_count <= 0xFFFFFFFF- ):- raise ValueError("Native frame count must be a positive uint32 or None.")- if output_width < 64 or output_height < 64:- raise ValueError("Neural dimensions must be at least 64×64.")- self.controller = controller- self._streaming = frame_count is None- self._expected_frames = frame_count- self._processed_frames = 0- self._next_frame_index: int | None = None- self.completed_frames: int | None = None- self.closed = False- self.factor = factor- self.mode = mode- self.native_settings = native_settings- self.composition_mask = mask_selection(composition_mask)- self.gpu = gpu- self.runtime_bundle = runtime_bundle- self.output_width = int(output_width)- self.output_height = int(output_height)- self.render_width = int(output_width)- self.render_height = int(output_height)- self.minimum_width = 64- self.minimum_height = 64- self.maximum_width = 16384- self.maximum_height = 16384- self.setup_result = 1- self.process_timings = {- "input_conversion_seconds": 0.0,- "input_transfer_seconds": 0.0,- "evaluation_wait_seconds": 0.0,- "output_transfer_seconds": 0.0,- "output_conversion_seconds": 0.0,- "optical_flow_seconds": 0.0,- "stabilization_seconds": 0.0,- }- if native_settings.get("gpu_mode", True) is not True:- raise ValueError("Neural Rendering requires CUDA/D3D12 GPU processing.")- self.cuda_video = bool(cuda_video)- self.diagnostics = BridgeSessionDiagnostics(- gpu_mode=True,- memory_path="cuda_d3d12_shared" if self.cuda_video else "host_cuda_d3d12_shared",- )- self._input_float = (- None if self.cuda_video else np.empty(- (self.output_height, self.output_width, 3), dtype=np.float32- )- )- self._output_float = (- None if self._input_float is None else np.empty_like(self._input_float)- )- self._shimmer_suppression = float(- native_settings.get("shimmer_suppression", 0.0)- )- self._host_stabilizer_enabled = bool(- not self.cuda_video- and self._input_float is not None- and self._shimmer_suppression > 0.0- )- self._host_flow = (- cv2.DISOpticalFlow_create(cv2.DISOPTICAL_FLOW_PRESET_MEDIUM)- if self._host_stabilizer_enabled- else None- )- if self._host_stabilizer_enabled:- host_y, host_x = np.mgrid[- 0:self.output_height, 0:self.output_width- ].astype(np.float32)- self._host_grid_x: np.ndarray | None = host_x- self._host_grid_y: np.ndarray | None = host_y- else:- self._host_grid_x = None- self._host_grid_y = None- self._host_previous_source: np.ndarray | None = None- self._host_previous_residual: np.ndarray | None = None- self._host_stabilized_frames = 0- # Host-output paths stabilize the final composed residual. Suppress- # the earlier native residual blend there to avoid filtering twice;- # depth/motion remain bound to every NGX evaluation.- self._host_bridge_settings = dict(native_settings)- if self._host_stabilizer_enabled:- self._host_bridge_settings["shimmer_suppression"] = 0.0- self._cuda_buffers: CudaFrameBuffers | None = None- self._mask_host = prepare_nr_mask(- self.composition_mask, self.output_width, self.output_height,- int(native_settings.get("mask_feather", 0)),- )- self._cuda_mask: CudaMaskBuffer | None = None- self._logs: list[str] = []- self._temporal_status_cache: dict[str, Any] = {}- status = BRIDGE_MANAGER.initialize(gpu)- self.bridge_status = {- **status,- "memory_path": self.diagnostics.memory_path,- "neural_dimensions": {- "width": self.output_width,- "height": self.output_height,- },- "resize_method": "none" if factor == 1.0 else "lanczos",- "nr_passes": int(native_settings.get("nr_passes", 1)),- "allocated_feature_instances": int(native_settings.get("nr_passes", 1)),- "composition": {- "color_strength": float(native_settings.get("color_strength", 1.0)),- "tone_preservation": float(native_settings.get("tone_preservation", 0.0)),- "face_skin_protection": float(native_settings.get("face_skin_protection", 0.0)),- "grain_preservation": float(native_settings.get("grain_preservation", 0.0)),- "mask": mask_report(self.composition_mask, int(native_settings.get("mask_feather", 0))),- "cuda_mask_uploads": 0,- "cuda_mask_upload_bytes": 0,- },- "temporal_stabilization": {- "shimmer_suppression": float(native_settings.get("shimmer_suppression", 0.0)),- "motion_backend": "initializing",- "motion_fallback": "bundled_gpu_lucas_kanade",- "depth_bound": False,- "motion_bound": False,- "optical_flow_seconds": 0.0,- "stabilization_seconds": 0.0,- "stabilizer_backend": (- "host_final_composed_residual"- if self._host_stabilizer_enabled- else "native_gpu_residual"- ),- },- }- BRIDGE_MANAGER.open_session()- self._manager_open = True- self._vram_tracker = GPUVramTracker(int(gpu.get("index", 0)))- self._vram_status: dict[str, object] | None = None- try:- if not self.cuda_video:- self._cuda_buffers = BRIDGE_MANAGER.create_cuda_buffers(- self.output_width, self.output_height- )- if self._mask_host is not None:- self._cuda_mask = BRIDGE_MANAGER.create_cuda_mask(self._mask_host)- self.bridge_status["composition"]["cuda_mask_uploads"] = 1- self.bridge_status["composition"]["cuda_mask_upload_bytes"] = int(- self._cuda_mask.byte_count- )- self._logs.append(- json.dumps(- {"event": "session_open", **self.bridge_status},- sort_keys=True,- separators=(",", ":"),- )- )- except Exception:- self._vram_tracker.close()- if self._cuda_mask is not None:- with contextlib.suppress(Exception):- self._cuda_mask.close()- self._cuda_mask = None- if self._cuda_buffers is not None:- with contextlib.suppress(Exception):- self._cuda_buffers.close()- self._cuda_buffers = None- BRIDGE_MANAGER.close_session()- self._manager_open = False- raise-- @property- def bridge_logs(self) -> list[str]:- return list(self._logs)-- @property- def logs(self) -> list[str]:- return self.bridge_logs-- @property- def bridge_log_dropped_lines(self) -> int:- return 0-- def structured_status(self) -> dict[str, Any]:- temporal = dict(self.bridge_status.get("temporal_stabilization", {}))- current_temporal = BRIDGE_MANAGER.temporal_status()- if current_temporal and (- bool(current_temporal.get("depth_bound"))- or not self._temporal_status_cache- ):- self._temporal_status_cache = current_temporal- temporal.update(self._temporal_status_cache)- if self._host_stabilizer_enabled:- temporal["stabilizer_backend"] = "host_final_composed_residual"- temporal["optical_flow_seconds"] = float(- self.process_timings.get("optical_flow_seconds", 0.0)- )- temporal["stabilization_seconds"] = float(- self.process_timings.get("stabilization_seconds", 0.0)- )- else:- temporal["optical_flow_seconds"] = float(- temporal.get("optical_flow_seconds", 0.0)- )- temporal["stabilization_seconds"] = float(- temporal.get("stabilization_seconds", 0.0)- )- if self.diagnostics.frames:- # The native feature is released at the final logical-session- # boundary, so retain deterministic counters even when a report is- # assembled after close.- temporal["motion_backend"] = temporal.get("motion_backend") if (- temporal.get("motion_frames", 0)- ) else (- "nvidia_nvofa"- if bool(self.native_settings.get("prefer_nvof", False))- else "gpu_lucas_kanade"- )- temporal["motion_frames"] = max(- int(temporal.get("motion_frames", 0)), self.diagnostics.frames- )- temporal["reset_frames"] = max(- int(temporal.get("reset_frames", 0)), self.diagnostics.scene_resets + 1- )- temporal["stabilized_frames"] = max(- int(temporal.get("stabilized_frames", 0)),- self._host_stabilized_frames- if self._host_stabilizer_enabled- else (- self.diagnostics.frames- if float(self.native_settings.get("shimmer_suppression", 0.0)) > 0- else 0- ),- )- temporal["depth_bound"] = True- temporal["motion_bound"] = True- return {- **self.bridge_status,- **self.diagnostics.as_dict(),- "gpu_memory": self._vram_status or self._vram_tracker.snapshot(),- "temporal_stabilization": temporal,- }-- def update_composition_mask(self, selection: object | None, feather: int) -> None:- """Prepare a replacement mask completely before swapping it at a frame boundary."""- selected = mask_selection(selection)- prepared = prepare_nr_mask(- selected, self.output_width, self.output_height, int(feather)- )- replacement = None- if prepared is not None:- replacement = BRIDGE_MANAGER.create_cuda_mask(prepared)- previous = self._cuda_mask- composition = self.bridge_status.get("composition", {})- cuda_uploads = int(composition.get("cuda_mask_uploads", 0))- cuda_upload_bytes = int(composition.get("cuda_mask_upload_bytes", 0))- self._mask_host = prepared- self._cuda_mask = replacement- self.composition_mask = selected- self.bridge_status["composition"] = {- "color_strength": float(self.native_settings.get("color_strength", 1.0)),- "tone_preservation": float(self.native_settings.get("tone_preservation", 0.0)),- "face_skin_protection": float(self.native_settings.get("face_skin_protection", 0.0)),- "grain_preservation": float(self.native_settings.get("grain_preservation", 0.0)),- "mask": mask_report(selected, int(feather)),- "cuda_mask_uploads": cuda_uploads + int(replacement is not None),- "cuda_mask_upload_bytes": cuda_upload_bytes + (- int(replacement.byte_count) if replacement is not None else 0- ),- }- if previous is not None:- previous.close()-- def _capture_temporal_status(self) -> None:- current = BRIDGE_MANAGER.temporal_status()- if current:- self._temporal_status_cache = current-- def _stabilize_host_composition(self, *, reset: bool) -> None:- """Stabilize model-created detail after all composition controls."""- if not self._host_stabilizer_enabled:- return- assert self._input_float is not None and self._output_float is not None- current_source = self._input_float- current_residual = self._output_float - current_source- if reset or self._host_previous_source is None or self._host_previous_residual is None:- self._host_previous_source = current_source.copy()- self._host_previous_residual = current_residual.copy()- return-- flow_started = time.perf_counter()- previous_gray = cv2.cvtColor(- np.clip(self._host_previous_source * 255.0, 0.0, 255.0).astype(np.uint8),- cv2.COLOR_RGB2GRAY,- )- current_gray = cv2.cvtColor(- np.clip(current_source * 255.0, 0.0, 255.0).astype(np.uint8),- cv2.COLOR_RGB2GRAY,- )- assert self._host_flow is not None- # DIS directly estimates the requested current -> previous field.- flow = self._host_flow.calc(current_gray, previous_gray, None)- self.process_timings["optical_flow_seconds"] += time.perf_counter() - flow_started-- stabilization_started = time.perf_counter()- height, width = current_gray.shape- assert self._host_grid_x is not None and self._host_grid_y is not None- map_x = self._host_grid_x + flow[..., 0]- map_y = self._host_grid_y + flow[..., 1]- valid = (- (map_x >= 0.0) & (map_y >= 0.0)- & (map_x <= float(width - 1)) & (map_y <= float(height - 1))- )- warped_source = cv2.remap(- self._host_previous_source,- map_x,- map_y,- cv2.INTER_LINEAR,- borderMode=cv2.BORDER_CONSTANT,- )- warped_residual = cv2.remap(- self._host_previous_residual,- map_x,- map_y,- cv2.INTER_LINEAR,- borderMode=cv2.BORDER_CONSTANT,- )-- luma_weights = np.array((0.2126, 0.7152, 0.0722), dtype=np.float32)- luma_disagreement = np.abs(- np.sum((current_source - warped_source) * luma_weights, axis=2)- )- confidence = np.clip((0.10 - luma_disagreement) / 0.08, 0.0, 1.0)- confidence *= valid-- # Clamp reprojected history to the current residual's 3x3 envelope.- kernel = np.ones((3, 3), dtype=np.uint8)- neighborhood_low = cv2.erode(current_residual, kernel)- neighborhood_high = cv2.dilate(current_residual, kernel)- np.clip(- warped_residual,- neighborhood_low,- neighborhood_high,- out=warped_residual,- )- weight = (self._shimmer_suppression * confidence)[..., None]- stabilized_residual = current_residual * (1.0 - weight) + warped_residual * weight- np.add(current_source, stabilized_residual, out=self._output_float)- np.clip(self._output_float, 0.0, 1.0, out=self._output_float)-- self._host_previous_source = current_source.copy()- self._host_previous_residual = stabilized_residual.copy()- self._host_stabilized_frames += 1- self.process_timings["stabilization_seconds"] += (- time.perf_counter() - stabilization_started- )-- def process(- self,- *,- index: int,- rgba: np.ndarray,- motion: np.ndarray | None = None,- reset: bool,- pts: int,- output_buffer: np.ndarray | None = None,- ) -> tuple[np.ndarray, int]:- del motion- if self.controller.cancel.is_set():- raise Cancelled("Render stopped by user.")- if self.closed:- raise RuntimeError("The Neural Rendering bridge session is closed.")- if self._next_frame_index is None:- self._next_frame_index = int(index)- if index != self._next_frame_index:- raise ValueError("Neural Rendering frames must have consecutive uint32 indices.")- if rgba.dtype not in (np.uint8, np.uint16) or rgba.shape != (- self.output_height,- self.output_width,- 4,- ):- raise ValueError("Neural Rendering input must be RGBA8 or RGBA16 at final size.")- rgba = np.ascontiguousarray(rgba)- self.diagnostics.working_format = "rgba16le" if rgba.dtype == np.uint16 else "rgba8"- self.diagnostics.output_format = self.diagnostics.working_format- if output_buffer is None:- output = np.empty_like(rgba)- else:- output = output_buffer- if (- output.dtype != rgba.dtype- or output.shape != rgba.shape- or not output.flags.c_contiguous- ):- raise ValueError("Neural Rendering output buffer has the wrong shape or layout.")-- started = time.perf_counter()- assert self._input_float is not None and self._output_float is not None- max_sample = float(np.iinfo(rgba.dtype).max)- np.multiply(rgba[..., :3], 1.0 / max_sample, out=self._input_float, casting="unsafe")- self.process_timings["input_conversion_seconds"] += time.perf_counter() - started-- assert self._cuda_buffers is not None- upload, evaluate, download = BRIDGE_MANAGER.process_cuda(- self._input_float,- self._output_float,- self._cuda_buffers,- self._host_bridge_settings,- bool(reset),- self._mask_host,- self._cuda_mask,- )- self.process_timings["input_transfer_seconds"] += upload- self.process_timings["evaluation_wait_seconds"] += evaluate- self.process_timings["output_transfer_seconds"] += download-- self._stabilize_host_composition(reset=bool(reset))-- started = time.perf_counter()- np.multiply(- np.clip(self._output_float, 0.0, 1.0),- max_sample,- out=self._output_float,- )- np.rint(self._output_float, out=self._output_float)- np.copyto(output[..., :3], self._output_float, casting="unsafe")- output[..., 3] = rgba[..., 3]- self.process_timings["output_conversion_seconds"] += time.perf_counter() - started-- transferred = self._input_float.nbytes- self.diagnostics.upload_bytes += transferred- self.diagnostics.download_bytes += self._output_float.nbytes- self.diagnostics.frames += 1- self.diagnostics.feature_evaluations += int(self.native_settings.get("nr_passes", 1))- self.diagnostics.scene_resets += int(reset and index != 0)- self._processed_frames += 1- self._next_frame_index += 1- self._capture_temporal_status()- self._logs.append(- json.dumps(- {- "event": "frame",- "index": index,- "pts": pts,- "reset": bool(reset),- "ngx_result": "0x00000001",- "memory_path": self.diagnostics.memory_path,- },- sort_keys=True,- separators=(",", ":"),- )- )- if len(self._logs) > 500:- del self._logs[: len(self._logs) - 500]- return output, int(pts)-- def score_cuda_frame(self, frame: Any, *, color_matrix: int, color_range: int) -> tuple[float, bool]:- if self.controller.cancel.is_set():- raise Cancelled("Render stopped by user.")- return BRIDGE_MANAGER.score_cuda_video_frame(- frame, threshold=0.24, color_matrix=color_matrix, color_range=color_range- )-- def process_cuda_frame_to_host(- self,- *,- index: int,- frame: Any,- reset: bool,- scene_score: float,- pts: int,- color_matrix: int,- color_range: int,- rotation: int = 0,- chroma_location: int = 1,- output_buffer: np.ndarray | None = None,- ) -> tuple[np.ndarray, int]:- if self.controller.cancel.is_set():- raise Cancelled("Render stopped by user.")- if self.closed:- raise RuntimeError("The CUDA Neural Rendering session is unavailable.")- if self._next_frame_index is None:- self._next_frame_index = int(index)- if index != self._next_frame_index:- raise ValueError("Neural Rendering frames must have consecutive uint32 indices.")- output = output_buffer- if output is None:- output = np.empty((self.output_height, self.output_width, 4), dtype=np.uint8)- if (- output.dtype not in (np.uint8, np.uint16)- or output.shape != (self.output_height, self.output_width, 4)- or not output.flags.c_contiguous- ):- raise ValueError("CUDA-to-host output buffer has the wrong shape or layout.")- result, elapsed = BRIDGE_MANAGER.process_cuda_to_host_video_frame(- frame,- output,- settings=self.native_settings,- mask=self._mask_host,- cuda_mask=self._cuda_mask,- reset=reset,- timestamp=pts,- color_matrix=color_matrix,- color_range=color_range,- rotation=rotation,- chroma_location=chroma_location,- )- self.process_timings["evaluation_wait_seconds"] += elapsed- self.diagnostics.decode_backend = "nvdec"- self.diagnostics.working_format = "float32-rgb"- self.diagnostics.output_format = result["output_format"]- self.diagnostics.pixel_format = result["input_format"]- self.diagnostics.upload_bytes += int(result["upload_bytes"])- self.diagnostics.download_bytes += int(result["download_bytes"])- self.diagnostics.ngx_create_result = result["ngx_create_result"]- self.diagnostics.ngx_evaluate_result = result["ngx_evaluate_result"]- self.diagnostics.frames += 1- self.diagnostics.feature_evaluations += int(self.native_settings.get("nr_passes", 1))- self.diagnostics.scene_resets += int(reset and index != 0)- self._processed_frames += 1- self._next_frame_index += 1- self._capture_temporal_status()- self._logs.append(json.dumps({- "event": "frame", "index": index, "pts": pts,- "reset": bool(reset), "scene_score": float(scene_score),- "ngx_create_result": result["ngx_create_result"],- "ngx_evaluate_result": result["ngx_evaluate_result"],- "memory_path": self.diagnostics.memory_path,- "input_format": result["input_format"], "output_format": result["output_format"],- "upload_bytes": result["upload_bytes"],- "download_bytes": result["download_bytes"],- }, sort_keys=True, separators=(",", ":")))- if len(self._logs) > 500:- del self._logs[: len(self._logs) - 500]- return output, int(result["timestamp"])-- def process_video_frame(- self,- *,- index: int,- frame: Any | None = None,- rgba: np.ndarray | None = None,- reset: bool,- scene_score: float,- pts: int,- duration: int | None,- time_base: Any,- color_matrix: int,- color_range: int,- rotation: int = 0,- chroma_location: int = 1,- output_p010: bool = False,- ) -> tuple[Any, int]:- """Process a hardware or software decoded frame into CUDA NV12/P010."""- if self.controller.cancel.is_set():- raise Cancelled("Render stopped by user.")- if self.closed:- raise RuntimeError("The Neural Rendering bridge session is closed.")- if not self.cuda_video:- raise RuntimeError("The CUDA video frame boundary is not enabled.")- if self._next_frame_index is None:- self._next_frame_index = int(index)- if index != self._next_frame_index:- raise ValueError("Neural Rendering frames must have consecutive uint32 indices.")- output_format = FORMAT_P010 if output_p010 else FORMAT_NV12- if frame is not None and rgba is not None:- raise ValueError("Pass either a CUDA frame or host RGBA pixels, not both.")- if frame is not None:- output, result, elapsed = BRIDGE_MANAGER.process_cuda_video_frame(- frame,- output_width=self.output_width,- output_height=self.output_height,- output_format=output_format,- settings=self.native_settings,- mask=self._mask_host,- cuda_mask=self._cuda_mask,- reset=reset,- timestamp=pts,- color_matrix=color_matrix,- color_range=color_range,- rotation=rotation,- chroma_location=chroma_location,- )- self.diagnostics.decode_backend = "nvdec"- self.diagnostics.working_format = "float32-rgb"- elif rgba is not None:- rgba = np.ascontiguousarray(rgba)- if rgba.dtype not in (np.uint8, np.uint16):- raise ValueError("Software video input must be RGBA8 or RGBA16.")- if rgba.shape != (self.output_height, self.output_width, 4):- raise ValueError("Software video input must be RGBA at final neural dimensions.")- output, result, elapsed = BRIDGE_MANAGER.process_host_to_cuda_video_frame(- rgba,- output_format=output_format,- settings=self.native_settings,- mask=self._mask_host,- cuda_mask=self._cuda_mask,- reset=reset,- timestamp=pts,- color_matrix=color_matrix,- color_range=color_range,- time_base=time_base,- duration=duration,- )- self.diagnostics.decode_backend = "software"- self.diagnostics.working_format = "rgba16le" if rgba.dtype == np.uint16 else "rgba8"- else:- raise ValueError("A CUDA frame or host RGBA frame is required.")- output.pts = int(pts)- output.time_base = time_base- if duration is not None:- output.duration = int(duration)- self.process_timings["evaluation_wait_seconds"] += elapsed- self.diagnostics.encode_backend = "nvenc"- self.diagnostics.pixel_format = result["output_format"]- self.diagnostics.output_format = result["output_format"]- self.diagnostics.upload_bytes += int(result["upload_bytes"])- self.diagnostics.download_bytes += int(result["download_bytes"])- self.diagnostics.ngx_create_result = result["ngx_create_result"]- self.diagnostics.ngx_evaluate_result = result["ngx_evaluate_result"]- self.diagnostics.frames += 1- self.diagnostics.feature_evaluations += int(self.native_settings.get("nr_passes", 1))- self.diagnostics.scene_resets += int(reset and index != 0)- self._processed_frames += 1- self._next_frame_index += 1- self._capture_temporal_status()- event = {- "event": "frame",- "index": index,- "pts": pts,- "reset": bool(reset),- "scene_score": float(scene_score),- "ngx_create_result": result["ngx_create_result"],- "ngx_evaluate_result": result["ngx_evaluate_result"],- "memory_path": self.diagnostics.memory_path,- "input_format": result["input_format"],- "output_format": result["output_format"],- "upload_bytes": result["upload_bytes"],- "download_bytes": result["download_bytes"],- }- self._logs.append(json.dumps(event, sort_keys=True, separators=(",", ":")))- if len(self._logs) > 500:- del self._logs[: len(self._logs) - 500]- return output, int(result["timestamp"])-- def close(self) -> None:- if self.closed:- return- if self.controller.cancel.is_set():- self.abort()- raise Cancelled("Render stopped by user.")- if self._streaming and not self._processed_frames:- self.abort()- raise RuntimeError("The input contains no decodable frames.")- if self._expected_frames is not None and self._processed_frames != self._expected_frames:- self.abort()- raise RuntimeError(- f"Neural Rendering processed {self._processed_frames} of "- f"{self._expected_frames} expected frames."- )- self.completed_frames = self._processed_frames- self._close_resources()-- def _close_resources(self) -> None:- if self.closed:- return- self._vram_tracker.close()- self._vram_status = self._vram_tracker.snapshot()- if self._cuda_buffers is not None:- self._cuda_buffers.close()- self._cuda_buffers = None- if self._cuda_mask is not None:- self._cuda_mask.close()- self._cuda_mask = None- if self._manager_open:- current_temporal = BRIDGE_MANAGER.temporal_status()- if current_temporal:- self._temporal_status_cache = current_temporal- BRIDGE_MANAGER.close_session()- self._manager_open = False- self.closed = True-- def abort(self) -> None:- self._close_resources()---def verify_feature_18(- bridge_logs: list[str], bridge_status: dict[str, Any] | str | None = None-) -> dict[str, object]:- """Return structured feature evidence without parsing external text logs."""- status = bridge_status if isinstance(bridge_status, dict) else {}- frames = 0- for line in bridge_logs:- try:- frames += int(json.loads(line).get("event") == "frame")- except (TypeError, ValueError, json.JSONDecodeError):- continue- return {- "bridge_status": status,- "feature_id": 18,- "feature_created": True,- "feature_evaluated": frames > 0,- "successful_frames": frames,- "evidence": list(bridge_logs[-20:]),- }---@dataclass(slots=True)-class PreparedRuntime:- gpu: dict[str, Any]- gpus: tuple[dict[str, Any], ...]- runtime_bundle: dict[str, Any]- encoder_inventory: dict[str, bool]- warmed_files: tuple[str, ...]- _mappings: list[mmap.mmap] = field(default_factory=list, repr=False)-- def close(self) -> None:- while self._mappings:- mapping = self._mappings.pop()- try:- mapping.close()- except (BufferError, OSError):- pass---_PREPARE_LOCK = threading.Lock()-_PREPARED: PreparedRuntime | None = None---def _warm_mapping(path: Path) -> mmap.mmap | None:- if not path.is_file() or path.stat().st_size == 0:- return None- with path.open("rb") as stream:- mapping = mmap.mmap(stream.fileno(), 0, access=mmap.ACCESS_READ)- checksum = 0- # Touch every OS page so the complete installed runtime is resident in the- # file cache before the window is shown, rather than faulting pages later.- for offset in range(0, len(mapping), mmap.PAGESIZE):- checksum ^= mapping[offset]- checksum ^= mapping[-1]- del checksum- return mapping---def _encoder_inventory() -> dict[str, bool]:- result = subprocess.run(- [str(FFMPEG), "-hide_banner", "-encoders"],- capture_output=True,- text=True,- encoding="utf-8",- errors="replace",- creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),- )- if result.returncode:- raise RuntimeError(result.stderr.strip() or "FFmpeg encoder inventory failed.")- output = result.stdout- return {- "h264_nvenc": "h264_nvenc" in output,- "hevc_nvenc": "hevc_nvenc" in output,- "av1_nvenc": "av1_nvenc" in output,- "prores_ks": "prores_ks" in output,- "ffv1": "ffv1" in output,- }---def prepare_runtime() -> PreparedRuntime:- global _PREPARED- if _PREPARED is not None:- return _PREPARED- with _PREPARE_LOCK:- if _PREPARED is not None:- return _PREPARED- validate_runtime_files()- BRIDGE_MANAGER.preload()- gpus = detect_gpus()- runtime_bundle = inspect_runtime_bundle()- gpu = resolve_runtime_ai_gpu(gpus, runtime_bundle)- inventory = _encoder_inventory()- required_paths = (DLSSNR_BRIDGE, DLSSNR_CALLER_SHIM, NEURAL_RUNTIME, FFMPEG, FFPROBE)- optional_paths = (- DLSSG_DIR / "neuroframe_engine_frame_interpolation.dll",- DLSSG_DIR / "nvngx_dlssg.dll",- RUNTIME / "rtx_video" / "neuroframe_engine_upscaling.dll",- RUNTIME / "rtx_video" / "nvngx_vsr.dll",- RUNTIME / "rtx_video" / "nvngx_truehdr.dll",- )- mappings: list[mmap.mmap] = []- warmed_paths: list[Path] = []- try:- for path in required_paths:- mapping = _warm_mapping(path)- if mapping is not None:- mappings.append(mapping)- warmed_paths.append(path)- except Exception:- for mapping in mappings:- mapping.close()- raise- for path in optional_paths:- try:- mapping = _warm_mapping(path)- if mapping is not None:- mappings.append(mapping)- warmed_paths.append(path)- except Exception:- # A damaged optional feature must not disable Neural Rendering.- continue- _PREPARED = PreparedRuntime(- gpu=dict(gpu),- gpus=tuple(dict(device) for device in gpus),- runtime_bundle=runtime_bundle,- encoder_inventory=inventory,- warmed_files=tuple(str(path.resolve()) for path in warmed_paths),- _mappings=mappings,- )- return _PREPARED---def close_prepared_runtime() -> None:- global _PREPARED- with _PREPARE_LOCK:- prepared = _PREPARED- _PREPARED = None- if prepared is not None:- prepared.close()+ interpolation: str = "Lanczos4", controller=None) -> np.ndarray:+ from .ffmpeg.filters import resize_fit as vulkan_resize+ return vulkan_resize(rgba, width, height, interpolation=interpolation, controller=controller)+++def rotate_frame(frame: np.ndarray, rotation: int, *, controller=None) -> np.ndarray:+ if rotation not in (90, 180, 270):+ return frame+ from .ffmpeg.filters import filter_array+ from .ffmpeg.vulkan import libplacebo+ width = frame.shape[0] if rotation != 180 else frame.shape[1]+ height = frame.shape[1] if rotation != 180 else frame.shape[0]+ graph = libplacebo(f"rotate={rotation // 90}:w={width}:h={height}")+ return filter_array(frame, graph, width=width, height=height, controller=controller)+++def validate_runtime_files() -> None:+ required = [FFMPEG, FFPROBE, DLSSNR_BRIDGE, DLSSNR_CALLER_SHIM, NEURAL_RUNTIME]+ missing = [str(path) for path in required if not path.is_file()]+ if missing:+ raise RuntimeError(+ "The Neural Rendering runtime is incomplete:\n" + "\n".join(missing)+ )+++class DLSSFrameSession:+ """Virtual feature-18 render session running on the shared system bridge."""++ def __init__(+ self,+ *,+ input_width: int,+ input_height: int,+ output_width: int,+ output_height: int,+ frame_count: int | None,+ warmup_frames: int,+ factor: float,+ mode: dict[str, str | int],+ native_settings: dict[str, int | float | bool],+ gpu: dict[str, Any],+ runtime_bundle: dict[str, Any],+ controller: JobController,+ cuda_video: bool = False,+ composition_mask: object | None = None,+ ) -> None:+ del input_width, input_height, warmup_frames+ if frame_count is not None and (+ isinstance(frame_count, bool)+ or not isinstance(frame_count, int)+ or not 0 < frame_count <= 0xFFFFFFFF+ ):+ raise ValueError("Native frame count must be a positive uint32 or None.")+ if output_width < 64 or output_height < 64:+ raise ValueError("Neural dimensions must be at least 64×64.")+ self.controller = controller+ self._streaming = frame_count is None+ self._expected_frames = frame_count+ self._processed_frames = 0+ self._next_frame_index: int | None = None+ self.completed_frames: int | None = None+ self.closed = False+ self.factor = factor+ self.mode = mode+ self.native_settings = native_settings+ self.composition_mask = mask_selection(composition_mask)+ self.gpu = gpu+ self.runtime_bundle = runtime_bundle+ self.output_width = int(output_width)+ self.output_height = int(output_height)+ self.render_width = int(output_width)+ self.render_height = int(output_height)+ self.minimum_width = 64+ self.minimum_height = 64+ self.maximum_width = 16384+ self.maximum_height = 16384+ self.setup_result = 1+ self.process_timings = {+ "input_conversion_seconds": 0.0,+ "input_transfer_seconds": 0.0,+ "evaluation_wait_seconds": 0.0,+ "output_transfer_seconds": 0.0,+ "output_conversion_seconds": 0.0,+ "optical_flow_seconds": 0.0,+ "stabilization_seconds": 0.0,+ }+ if native_settings.get("gpu_mode", True) is not True:+ raise ValueError("Neural Rendering requires CUDA/D3D12 GPU processing.")+ self.cuda_video = bool(cuda_video)+ self.diagnostics = BridgeSessionDiagnostics(+ gpu_mode=True,+ memory_path="cuda_d3d12_shared" if self.cuda_video else "host_cuda_d3d12_shared",+ )+ self._input_float = (+ None if self.cuda_video else np.empty(+ (self.output_height, self.output_width, 3), dtype=np.float32+ )+ )+ self._output_float = (+ None if self._input_float is None else np.empty_like(self._input_float)+ )+ self._shimmer_suppression = float(+ native_settings.get("shimmer_suppression", 0.0)+ )+ self._host_stabilizer_enabled = bool(+ not self.cuda_video+ and self._input_float is not None+ and self._shimmer_suppression > 0.0+ )+ self._host_flow = (+ cv2.DISOpticalFlow_create(cv2.DISOPTICAL_FLOW_PRESET_MEDIUM)+ if self._host_stabilizer_enabled+ else None+ )+ if self._host_stabilizer_enabled:+ host_y, host_x = np.mgrid[+ 0:self.output_height, 0:self.output_width+ ].astype(np.float32)+ self._host_grid_x: np.ndarray | None = host_x+ self._host_grid_y: np.ndarray | None = host_y+ else:+ self._host_grid_x = None+ self._host_grid_y = None+ self._host_previous_source: np.ndarray | None = None+ self._host_previous_residual: np.ndarray | None = None+ self._host_stabilized_frames = 0+ # Host-output paths stabilize the final composed residual. Suppress+ # the earlier native residual blend there to avoid filtering twice;+ # depth/motion remain bound to every NGX evaluation.+ self._host_bridge_settings = dict(native_settings)+ if self._host_stabilizer_enabled:+ self._host_bridge_settings["shimmer_suppression"] = 0.0+ self._cuda_buffers: CudaFrameBuffers | None = None+ self._mask_host = prepare_nr_mask(+ self.composition_mask, self.output_width, self.output_height,+ int(native_settings.get("mask_feather", 0)),+ )+ self._cuda_mask: CudaMaskBuffer | None = None+ self._logs: list[str] = []+ self._temporal_status_cache: dict[str, Any] = {}+ status = BRIDGE_MANAGER.initialize(gpu)+ self.bridge_status = {+ **status,+ "memory_path": self.diagnostics.memory_path,+ "neural_dimensions": {+ "width": self.output_width,+ "height": self.output_height,+ },+ "resize_method": "none" if factor == 1.0 else "lanczos",+ "nr_passes": int(native_settings.get("nr_passes", 1)),+ "allocated_feature_instances": int(native_settings.get("nr_passes", 1)),+ "composition": {+ "color_strength": float(native_settings.get("color_strength", 1.0)),+ "tone_preservation": float(native_settings.get("tone_preservation", 0.0)),+ "face_skin_protection": float(native_settings.get("face_skin_protection", 0.0)),+ "grain_preservation": float(native_settings.get("grain_preservation", 0.0)),+ "mask": mask_report(self.composition_mask, int(native_settings.get("mask_feather", 0))),+ "cuda_mask_uploads": 0,+ "cuda_mask_upload_bytes": 0,+ },+ "temporal_stabilization": {+ "shimmer_suppression": float(native_settings.get("shimmer_suppression", 0.0)),+ "motion_backend": "initializing",+ "motion_fallback": "bundled_gpu_lucas_kanade",+ "depth_bound": False,+ "motion_bound": False,+ "optical_flow_seconds": 0.0,+ "stabilization_seconds": 0.0,+ "stabilizer_backend": (+ "host_final_composed_residual"+ if self._host_stabilizer_enabled+ else "native_gpu_residual"+ ),+ },+ }+ BRIDGE_MANAGER.open_session()+ self._manager_open = True+ self._vram_tracker = GPUVramTracker(int(gpu.get("index", 0)))+ self._vram_status: dict[str, object] | None = None+ try:+ if not self.cuda_video:+ self._cuda_buffers = BRIDGE_MANAGER.create_cuda_buffers(+ self.output_width, self.output_height+ )+ if self._mask_host is not None:+ self._cuda_mask = BRIDGE_MANAGER.create_cuda_mask(self._mask_host)+ self.bridge_status["composition"]["cuda_mask_uploads"] = 1+ self.bridge_status["composition"]["cuda_mask_upload_bytes"] = int(+ self._cuda_mask.byte_count+ )+ self._logs.append(+ json.dumps(+ {"event": "session_open", **self.bridge_status},+ sort_keys=True,+ separators=(",", ":"),+ )+ )+ except Exception:+ self._vram_tracker.close()+ if self._cuda_mask is not None:+ with contextlib.suppress(Exception):+ self._cuda_mask.close()+ self._cuda_mask = None+ if self._cuda_buffers is not None:+ with contextlib.suppress(Exception):+ self._cuda_buffers.close()+ self._cuda_buffers = None+ BRIDGE_MANAGER.close_session()+ self._manager_open = False+ raise++ @property+ def bridge_logs(self) -> list[str]:+ return list(self._logs)++ @property+ def logs(self) -> list[str]:+ return self.bridge_logs++ @property+ def bridge_log_dropped_lines(self) -> int:+ return 0++ def structured_status(self) -> dict[str, Any]:+ temporal = dict(self.bridge_status.get("temporal_stabilization", {}))+ current_temporal = BRIDGE_MANAGER.temporal_status()+ if current_temporal and (+ bool(current_temporal.get("depth_bound"))+ or not self._temporal_status_cache+ ):+ self._temporal_status_cache = current_temporal+ temporal.update(self._temporal_status_cache)+ if self._host_stabilizer_enabled:+ temporal["stabilizer_backend"] = "host_final_composed_residual"+ temporal["optical_flow_seconds"] = float(+ self.process_timings.get("optical_flow_seconds", 0.0)+ )+ temporal["stabilization_seconds"] = float(+ self.process_timings.get("stabilization_seconds", 0.0)+ )+ else:+ temporal["optical_flow_seconds"] = float(+ temporal.get("optical_flow_seconds", 0.0)+ )+ temporal["stabilization_seconds"] = float(+ temporal.get("stabilization_seconds", 0.0)+ )+ if self.diagnostics.frames:+ # The native feature is released at the final logical-session+ # boundary, so retain deterministic counters even when a report is+ # assembled after close.+ temporal["motion_backend"] = temporal.get("motion_backend") if (+ temporal.get("motion_frames", 0)+ ) else (+ "nvidia_nvofa"+ if bool(self.native_settings.get("prefer_nvof", False))+ else "gpu_lucas_kanade"+ )+ temporal["motion_frames"] = max(+ int(temporal.get("motion_frames", 0)), self.diagnostics.frames+ )+ temporal["reset_frames"] = max(+ int(temporal.get("reset_frames", 0)), self.diagnostics.scene_resets + 1+ )+ temporal["stabilized_frames"] = max(+ int(temporal.get("stabilized_frames", 0)),+ self._host_stabilized_frames+ if self._host_stabilizer_enabled+ else (+ self.diagnostics.frames+ if float(self.native_settings.get("shimmer_suppression", 0.0)) > 0+ else 0+ ),+ )+ temporal["depth_bound"] = True+ temporal["motion_bound"] = True+ return {+ **self.bridge_status,+ **self.diagnostics.as_dict(),+ "gpu_memory": self._vram_status or self._vram_tracker.snapshot(),+ "temporal_stabilization": temporal,+ }++ def update_composition_mask(self, selection: object | None, feather: int) -> None:+ """Prepare a replacement mask completely before swapping it at a frame boundary."""+ selected = mask_selection(selection)+ prepared = prepare_nr_mask(+ selected, self.output_width, self.output_height, int(feather)+ )+ replacement = None+ if prepared is not None:+ replacement = BRIDGE_MANAGER.create_cuda_mask(prepared)+ previous = self._cuda_mask+ composition = self.bridge_status.get("composition", {})+ cuda_uploads = int(composition.get("cuda_mask_uploads", 0))+ cuda_upload_bytes = int(composition.get("cuda_mask_upload_bytes", 0))+ self._mask_host = prepared+ self._cuda_mask = replacement+ self.composition_mask = selected+ self.bridge_status["composition"] = {+ "color_strength": float(self.native_settings.get("color_strength", 1.0)),+ "tone_preservation": float(self.native_settings.get("tone_preservation", 0.0)),+ "face_skin_protection": float(self.native_settings.get("face_skin_protection", 0.0)),+ "grain_preservation": float(self.native_settings.get("grain_preservation", 0.0)),+ "mask": mask_report(selected, int(feather)),+ "cuda_mask_uploads": cuda_uploads + int(replacement is not None),+ "cuda_mask_upload_bytes": cuda_upload_bytes + (+ int(replacement.byte_count) if replacement is not None else 0+ ),+ }+ if previous is not None:+ previous.close()++ def _capture_temporal_status(self) -> None:+ current = BRIDGE_MANAGER.temporal_status()+ if current:+ self._temporal_status_cache = current++ def _stabilize_host_composition(self, *, reset: bool) -> None:+ """Stabilize model-created detail after all composition controls."""+ if not self._host_stabilizer_enabled:+ return+ assert self._input_float is not None and self._output_float is not None+ current_source = self._input_float+ current_residual = self._output_float - current_source+ if reset or self._host_previous_source is None or self._host_previous_residual is None:+ self._host_previous_source = current_source.copy()+ self._host_previous_residual = current_residual.copy()+ return++ flow_started = time.perf_counter()+ previous_gray = cv2.cvtColor(+ np.clip(self._host_previous_source * 255.0, 0.0, 255.0).astype(np.uint8),+ cv2.COLOR_RGB2GRAY,+ )+ current_gray = cv2.cvtColor(+ np.clip(current_source * 255.0, 0.0, 255.0).astype(np.uint8),+ cv2.COLOR_RGB2GRAY,+ )+ assert self._host_flow is not None+ # DIS directly estimates the requested current -> previous field.+ flow = self._host_flow.calc(current_gray, previous_gray, None)+ self.process_timings["optical_flow_seconds"] += time.perf_counter() - flow_started++ stabilization_started = time.perf_counter()+ height, width = current_gray.shape+ assert self._host_grid_x is not None and self._host_grid_y is not None+ map_x = self._host_grid_x + flow[..., 0]+ map_y = self._host_grid_y + flow[..., 1]+ valid = (+ (map_x >= 0.0) & (map_y >= 0.0)+ & (map_x <= float(width - 1)) & (map_y <= float(height - 1))+ )+ warped_source = cv2.remap(+ self._host_previous_source,+ map_x,+ map_y,+ cv2.INTER_LINEAR,+ borderMode=cv2.BORDER_CONSTANT,+ )+ warped_residual = cv2.remap(+ self._host_previous_residual,+ map_x,+ map_y,+ cv2.INTER_LINEAR,+ borderMode=cv2.BORDER_CONSTANT,+ )++ luma_weights = np.array((0.2126, 0.7152, 0.0722), dtype=np.float32)+ luma_disagreement = np.abs(+ np.sum((current_source - warped_source) * luma_weights, axis=2)+ )+ confidence = np.clip((0.10 - luma_disagreement) / 0.08, 0.0, 1.0)+ confidence *= valid++ # Clamp reprojected history to the current residual's 3x3 envelope.+ kernel = np.ones((3, 3), dtype=np.uint8)+ neighborhood_low = cv2.erode(current_residual, kernel)+ neighborhood_high = cv2.dilate(current_residual, kernel)+ np.clip(+ warped_residual,+ neighborhood_low,+ neighborhood_high,+ out=warped_residual,+ )+ weight = (self._shimmer_suppression * confidence)[..., None]+ stabilized_residual = current_residual * (1.0 - weight) + warped_residual * weight+ np.add(current_source, stabilized_residual, out=self._output_float)+ np.clip(self._output_float, 0.0, 1.0, out=self._output_float)++ self._host_previous_source = current_source.copy()+ self._host_previous_residual = stabilized_residual.copy()+ self._host_stabilized_frames += 1+ self.process_timings["stabilization_seconds"] += (+ time.perf_counter() - stabilization_started+ )++ def process(+ self,+ *,+ index: int,+ rgba: np.ndarray,+ motion: np.ndarray | None = None,+ reset: bool,+ pts: int,+ output_buffer: np.ndarray | None = None,+ ) -> tuple[np.ndarray, int]:+ del motion+ if self.controller.cancel.is_set():+ raise Cancelled("Render stopped by user.")+ if self.closed:+ raise RuntimeError("The Neural Rendering bridge session is closed.")+ if self._next_frame_index is None:+ self._next_frame_index = int(index)+ if index != self._next_frame_index:+ raise ValueError("Neural Rendering frames must have consecutive uint32 indices.")+ if rgba.dtype not in (np.uint8, np.uint16) or rgba.shape != (+ self.output_height,+ self.output_width,+ 4,+ ):+ raise ValueError("Neural Rendering input must be RGBA8 or RGBA16 at final size.")+ rgba = np.ascontiguousarray(rgba)+ self.diagnostics.working_format = "rgba16le" if rgba.dtype == np.uint16 else "rgba8"+ self.diagnostics.output_format = self.diagnostics.working_format+ if output_buffer is None:+ output = np.empty_like(rgba)+ else:+ output = output_buffer+ if (+ output.dtype != rgba.dtype+ or output.shape != rgba.shape+ or not output.flags.c_contiguous+ ):+ raise ValueError("Neural Rendering output buffer has the wrong shape or layout.")++ started = time.perf_counter()+ assert self._input_float is not None and self._output_float is not None+ max_sample = float(np.iinfo(rgba.dtype).max)+ np.multiply(rgba[..., :3], 1.0 / max_sample, out=self._input_float, casting="unsafe")+ self.process_timings["input_conversion_seconds"] += time.perf_counter() - started++ assert self._cuda_buffers is not None+ upload, evaluate, download = BRIDGE_MANAGER.process_cuda(+ self._input_float,+ self._output_float,+ self._cuda_buffers,+ self._host_bridge_settings,+ bool(reset),+ self._mask_host,+ self._cuda_mask,+ )+ self.process_timings["input_transfer_seconds"] += upload+ self.process_timings["evaluation_wait_seconds"] += evaluate+ self.process_timings["output_transfer_seconds"] += download++ self._stabilize_host_composition(reset=bool(reset))++ started = time.perf_counter()+ np.multiply(+ np.clip(self._output_float, 0.0, 1.0),+ max_sample,+ out=self._output_float,+ )+ np.rint(self._output_float, out=self._output_float)+ np.copyto(output[..., :3], self._output_float, casting="unsafe")+ output[..., 3] = rgba[..., 3]+ self.process_timings["output_conversion_seconds"] += time.perf_counter() - started++ transferred = self._input_float.nbytes+ self.diagnostics.upload_bytes += transferred+ self.diagnostics.download_bytes += self._output_float.nbytes+ self.diagnostics.frames += 1+ self.diagnostics.feature_evaluations += int(self.native_settings.get("nr_passes", 1))+ self.diagnostics.scene_resets += int(reset and index != 0)+ self._processed_frames += 1+ self._next_frame_index += 1+ self._capture_temporal_status()+ self._logs.append(+ json.dumps(+ {+ "event": "frame",+ "index": index,+ "pts": pts,+ "reset": bool(reset),+ "ngx_result": "0x00000001",+ "memory_path": self.diagnostics.memory_path,+ },+ sort_keys=True,+ separators=(",", ":"),+ )+ )+ if len(self._logs) > 500:+ del self._logs[: len(self._logs) - 500]+ return output, int(pts)++ def score_cuda_frame(self, frame: Any, *, color_matrix: int, color_range: int) -> tuple[float, bool]:+ if self.controller.cancel.is_set():+ raise Cancelled("Render stopped by user.")+ return BRIDGE_MANAGER.score_cuda_video_frame(+ frame, threshold=0.24, color_matrix=color_matrix, color_range=color_range+ )++ def process_cuda_frame_to_host(+ self,+ *,+ index: int,+ frame: Any,+ reset: bool,+ scene_score: float,+ pts: int,+ color_matrix: int,+ color_range: int,+ rotation: int = 0,+ chroma_location: int = 1,+ output_buffer: np.ndarray | None = None,+ ) -> tuple[np.ndarray, int]:+ if self.controller.cancel.is_set():+ raise Cancelled("Render stopped by user.")+ if self.closed:+ raise RuntimeError("The CUDA Neural Rendering session is unavailable.")+ if self._next_frame_index is None:+ self._next_frame_index = int(index)+ if index != self._next_frame_index:+ raise ValueError("Neural Rendering frames must have consecutive uint32 indices.")+ output = output_buffer+ if output is None:+ output = np.empty((self.output_height, self.output_width, 4), dtype=np.uint8)+ if (+ output.dtype not in (np.uint8, np.uint16)+ or output.shape != (self.output_height, self.output_width, 4)+ or not output.flags.c_contiguous+ ):+ raise ValueError("CUDA-to-host output buffer has the wrong shape or layout.")+ result, elapsed = BRIDGE_MANAGER.process_cuda_to_host_video_frame(+ frame,+ output,+ settings=self.native_settings,+ mask=self._mask_host,+ cuda_mask=self._cuda_mask,+ reset=reset,+ timestamp=pts,+ color_matrix=color_matrix,+ color_range=color_range,+ rotation=rotation,+ chroma_location=chroma_location,+ )+ self.process_timings["evaluation_wait_seconds"] += elapsed+ self.diagnostics.decode_backend = "nvdec"+ self.diagnostics.working_format = "float32-rgb"+ self.diagnostics.output_format = result["output_format"]+ self.diagnostics.pixel_format = result["input_format"]+ self.diagnostics.upload_bytes += int(result["upload_bytes"])+ self.diagnostics.download_bytes += int(result["download_bytes"])+ self.diagnostics.ngx_create_result = result["ngx_create_result"]+ self.diagnostics.ngx_evaluate_result = result["ngx_evaluate_result"]+ self.diagnostics.frames += 1+ self.diagnostics.feature_evaluations += int(self.native_settings.get("nr_passes", 1))+ self.diagnostics.scene_resets += int(reset and index != 0)+ self._processed_frames += 1+ self._next_frame_index += 1+ self._capture_temporal_status()+ self._logs.append(json.dumps({+ "event": "frame", "index": index, "pts": pts,+ "reset": bool(reset), "scene_score": float(scene_score),+ "ngx_create_result": result["ngx_create_result"],+ "ngx_evaluate_result": result["ngx_evaluate_result"],+ "memory_path": self.diagnostics.memory_path,+ "input_format": result["input_format"], "output_format": result["output_format"],+ "upload_bytes": result["upload_bytes"],+ "download_bytes": result["download_bytes"],+ }, sort_keys=True, separators=(",", ":")))+ if len(self._logs) > 500:+ del self._logs[: len(self._logs) - 500]+ return output, int(result["timestamp"])++ def process_video_frame(+ self,+ *,+ index: int,+ frame: Any | None = None,+ rgba: np.ndarray | None = None,+ reset: bool,+ scene_score: float,+ pts: int,+ duration: int | None,+ time_base: Any,+ color_matrix: int,+ color_range: int,+ rotation: int = 0,+ chroma_location: int = 1,+ output_p010: bool = False,+ ) -> tuple[Any, int]:+ """Process a hardware or software decoded frame into CUDA NV12/P010."""+ if self.controller.cancel.is_set():+ raise Cancelled("Render stopped by user.")+ if self.closed:+ raise RuntimeError("The Neural Rendering bridge session is closed.")+ if not self.cuda_video:+ raise RuntimeError("The CUDA video frame boundary is not enabled.")+ if self._next_frame_index is None:+ self._next_frame_index = int(index)+ if index != self._next_frame_index:+ raise ValueError("Neural Rendering frames must have consecutive uint32 indices.")+ output_format = FORMAT_P010 if output_p010 else FORMAT_NV12+ if frame is not None and rgba is not None:+ raise ValueError("Pass either a CUDA frame or host RGBA pixels, not both.")+ if frame is not None:+ output, result, elapsed = BRIDGE_MANAGER.process_cuda_video_frame(+ frame,+ output_width=self.output_width,+ output_height=self.output_height,+ output_format=output_format,+ settings=self.native_settings,+ mask=self._mask_host,+ cuda_mask=self._cuda_mask,+ reset=reset,+ timestamp=pts,+ color_matrix=color_matrix,+ color_range=color_range,+ rotation=rotation,+ chroma_location=chroma_location,+ )+ self.diagnostics.decode_backend = "nvdec"+ self.diagnostics.working_format = "float32-rgb"+ elif rgba is not None:+ rgba = np.ascontiguousarray(rgba)+ if rgba.dtype not in (np.uint8, np.uint16):+ raise ValueError("Software video input must be RGBA8 or RGBA16.")+ if rgba.shape != (self.output_height, self.output_width, 4):+ raise ValueError("Software video input must be RGBA at final neural dimensions.")+ output, result, elapsed = BRIDGE_MANAGER.process_host_to_cuda_video_frame(+ rgba,+ output_format=output_format,+ settings=self.native_settings,+ mask=self._mask_host,+ cuda_mask=self._cuda_mask,+ reset=reset,+ timestamp=pts,+ color_matrix=color_matrix,+ color_range=color_range,+ time_base=time_base,+ duration=duration,+ )+ self.diagnostics.decode_backend = "software"+ self.diagnostics.working_format = "rgba16le" if rgba.dtype == np.uint16 else "rgba8"+ else:+ raise ValueError("A CUDA frame or host RGBA frame is required.")+ output.pts = int(pts)+ output.time_base = time_base+ if duration is not None:+ output.duration = int(duration)+ self.process_timings["evaluation_wait_seconds"] += elapsed+ self.diagnostics.encode_backend = "nvenc"+ self.diagnostics.pixel_format = result["output_format"]+ self.diagnostics.output_format = result["output_format"]+ self.diagnostics.upload_bytes += int(result["upload_bytes"])+ self.diagnostics.download_bytes += int(result["download_bytes"])+ self.diagnostics.ngx_create_result = result["ngx_create_result"]+ self.diagnostics.ngx_evaluate_result = result["ngx_evaluate_result"]+ self.diagnostics.frames += 1+ self.diagnostics.feature_evaluations += int(self.native_settings.get("nr_passes", 1))+ self.diagnostics.scene_resets += int(reset and index != 0)+ self._processed_frames += 1+ self._next_frame_index += 1+ self._capture_temporal_status()+ event = {+ "event": "frame",+ "index": index,+ "pts": pts,+ "reset": bool(reset),+ "scene_score": float(scene_score),+ "ngx_create_result": result["ngx_create_result"],+ "ngx_evaluate_result": result["ngx_evaluate_result"],+ "memory_path": self.diagnostics.memory_path,+ "input_format": result["input_format"],+ "output_format": result["output_format"],+ "upload_bytes": result["upload_bytes"],+ "download_bytes": result["download_bytes"],+ }+ self._logs.append(json.dumps(event, sort_keys=True, separators=(",", ":")))+ if len(self._logs) > 500:+ del self._logs[: len(self._logs) - 500]+ return output, int(result["timestamp"])++ def close(self) -> None:+ if self.closed:+ return+ if self.controller.cancel.is_set():+ self.abort()+ raise Cancelled("Render stopped by user.")+ if self._streaming and not self._processed_frames:+ self.abort()+ raise RuntimeError("The input contains no decodable frames.")+ if self._expected_frames is not None and self._processed_frames != self._expected_frames:+ self.abort()+ raise RuntimeError(+ f"Neural Rendering processed {self._processed_frames} of "+ f"{self._expected_frames} expected frames."+ )+ self.completed_frames = self._processed_frames+ self._close_resources()++ def _close_resources(self) -> None:+ if self.closed:+ return+ self._vram_tracker.close()+ self._vram_status = self._vram_tracker.snapshot()+ if self._cuda_buffers is not None:+ self._cuda_buffers.close()+ self._cuda_buffers = None+ if self._cuda_mask is not None:+ self._cuda_mask.close()+ self._cuda_mask = None+ if self._manager_open:+ current_temporal = BRIDGE_MANAGER.temporal_status()+ if current_temporal:+ self._temporal_status_cache = current_temporal+ BRIDGE_MANAGER.close_session()+ self._manager_open = False+ self.closed = True++ def abort(self) -> None:+ self._close_resources()+++def verify_feature_18(+ bridge_logs: list[str], bridge_status: dict[str, Any] | str | None = None+) -> dict[str, object]:+ """Return structured feature evidence without parsing external text logs."""+ status = bridge_status if isinstance(bridge_status, dict) else {}+ frames = 0+ for line in bridge_logs:+ try:+ frames += int(json.loads(line).get("event") == "frame")+ except (TypeError, ValueError, json.JSONDecodeError):+ continue+ return {+ "bridge_status": status,+ "feature_id": 18,+ "feature_created": True,+ "feature_evaluated": frames > 0,+ "successful_frames": frames,+ "evidence": list(bridge_logs[-20:]),+ }+++@dataclass(slots=True)+class PreparedRuntime:+ gpu: dict[str, Any]+ gpus: tuple[dict[str, Any], ...]+ runtime_bundle: dict[str, Any]+ encoder_inventory: dict[str, bool]+ warmed_files: tuple[str, ...]+ _mappings: list[mmap.mmap] = field(default_factory=list, repr=False)++ def close(self) -> None:+ while self._mappings:+ mapping = self._mappings.pop()+ try:+ mapping.close()+ except (BufferError, OSError):+ pass+++_PREPARE_LOCK = threading.Lock()+_PREPARED: PreparedRuntime | None = None+++def _warm_mapping(path: Path) -> mmap.mmap | None:+ if not path.is_file() or path.stat().st_size == 0:+ return None+ with path.open("rb") as stream:+ mapping = mmap.mmap(stream.fileno(), 0, access=mmap.ACCESS_READ)+ checksum = 0+ # Touch every OS page so the complete installed runtime is resident in the+ # file cache before the window is shown, rather than faulting pages later.+ for offset in range(0, len(mapping), mmap.PAGESIZE):+ checksum ^= mapping[offset]+ checksum ^= mapping[-1]+ del checksum+ return mapping+++def _encoder_inventory() -> dict[str, bool]:+ result = subprocess.run(+ [str(FFMPEG), "-hide_banner", "-encoders"],+ capture_output=True,+ text=True,+ encoding="utf-8",+ errors="replace",+ creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),+ )+ if result.returncode:+ raise RuntimeError(result.stderr.strip() or "FFmpeg encoder inventory failed.")+ output = result.stdout+ return {+ "h264_nvenc": "h264_nvenc" in output,+ "hevc_nvenc": "hevc_nvenc" in output,+ "av1_nvenc": "av1_nvenc" in output,+ "prores_ks": "prores_ks" in output,+ "ffv1": "ffv1" in output,+ }+++def prepare_runtime() -> PreparedRuntime:+ global _PREPARED+ if _PREPARED is not None:+ return _PREPARED+ with _PREPARE_LOCK:+ if _PREPARED is not None:+ return _PREPARED+ validate_runtime_files()+ BRIDGE_MANAGER.preload()+ gpus = detect_gpus()+ runtime_bundle = inspect_runtime_bundle()+ gpu = resolve_runtime_ai_gpu(gpus, runtime_bundle)+ inventory = _encoder_inventory()+ required_paths = (DLSSNR_BRIDGE, DLSSNR_CALLER_SHIM, NEURAL_RUNTIME, FFMPEG, FFPROBE)+ optional_paths = (+ DLSSG_DIR / "neuroframe_engine_frame_interpolation.dll",+ DLSSG_DIR / "nvngx_dlssg.dll",+ RUNTIME / "rtx_video" / "neuroframe_engine_upscaling.dll",+ RUNTIME / "rtx_video" / "nvngx_vsr.dll",+ RUNTIME / "rtx_video" / "nvngx_truehdr.dll",+ )+ mappings: list[mmap.mmap] = []+ warmed_paths: list[Path] = []+ try:+ for path in required_paths:+ mapping = _warm_mapping(path)+ if mapping is not None:+ mappings.append(mapping)+ warmed_paths.append(path)+ except Exception:+ for mapping in mappings:+ mapping.close()+ raise+ for path in optional_paths:+ try:+ mapping = _warm_mapping(path)+ if mapping is not None:+ mappings.append(mapping)+ warmed_paths.append(path)+ except Exception:+ # A damaged optional feature must not disable Neural Rendering.+ continue+ _PREPARED = PreparedRuntime(+ gpu=dict(gpu),+ gpus=tuple(dict(device) for device in gpus),+ runtime_bundle=runtime_bundle,+ encoder_inventory=inventory,+ warmed_files=tuple(str(path.resolve()) for path in warmed_paths),+ _mappings=mappings,+ )+ return _PREPARED+++def close_prepared_runtime() -> None:+ global _PREPARED+ with _PREPARE_LOCK:+ prepared = _PREPARED+ _PREPARED = None+ if prepared is not None:+ prepared.close()diff --git a/src/desktop/app.py b/src/desktop/app.pyindex 64dcfc3..18291aa 100644--- a/src/desktop/app.py+++ b/src/desktop/app.py@@ -6,15 +6,22 @@ import sysimport timefrom pathlib import Path-from PySide6.QtCore import QUrl, Qt+from ..portable import configure_portable_environment++configure_portable_environment()++from PySide6.QtCore import QRect, QUrl, Qtfrom PySide6.QtGui import QGuiApplication, QIconfrom PySide6.QtQml import QQmlApplicationEngine-from ..core.paths import ROOT, OUTPUTS, LOGS, LIVE_DIR+from ..core.paths import ROOT, OUTPUTS, LOGS, LIVE_DIR, JOBSfrom ..core.cache_cleanup import cleanup_old_cachesfrom ..core import app_logfrom .image_provider import IconImageProvider, PreviewImageProviderfrom .bridge import AppBridge+from .preview_player import PreviewPlayer+from .window_geometry import restore_window_geometry+from .window_focus import ClickFocusFilterfrom .win_frameless import install_win_chrome, remove_win_chrome, ensure_win_style, log_native_chrome@@ -276,6 +283,7 @@ def launch_desktop() -> int:OUTPUTS.mkdir(exist_ok=True)LOGS.mkdir(exist_ok=True)LIVE_DIR.mkdir(exist_ok=True)+ JOBS.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. Finish the sweep before showing the UI.@@ -291,7 +299,12 @@ def launch_desktop() -> int:QGuiApplication.setHighDpiScaleFactorRoundingPolicy(Qt.HighDpiScaleFactorRoundingPolicy.PassThrough)+ # Use FFmpeg for the original-media player as well as export formats.+ # Cached previews use our direct 10-bit frame player below.+ os.environ["QT_MEDIA_BACKEND"] = "ffmpeg"app = QGuiApplication(sys.argv)+ from PySide6.QtQml import qmlRegisterType+ qmlRegisterType(PreviewPlayer, "VisualEnhancer", 1, 0, "PreviewPlayer")app.setApplicationName("Visual Enhancer")app.setApplicationDisplayName("Visual Enhancer")app.setOrganizationName("Merserk")@@ -313,6 +326,7 @@ def launch_desktop() -> int:engine.addImageProvider("preview", image_provider)engine.addImageProvider("icons", IconImageProvider())engine.rootContext().setContextProperty("backend", bridge)+ bridge.languageChanged.connect(engine.retranslate)qml_path = Path(__file__).resolve().parent / "qml" / "Main.qml"engine.load(QUrl.fromLocalFile(str(qml_path)))@@ -328,6 +342,12 @@ def launch_desktop() -> int:return 1root_window = engine.rootObjects()[0]+ focus_filter = ClickFocusFilter(root_window)+ restore_window_geometry(+ root_window,+ QRect(bridge.windowX, bridge.windowY, bridge.windowWidth, bridge.windowHeight),+ has_position=(bridge.windowX, bridge.windowY) != (-1, -1),+ )root_window.create()# Brand the live taskbar button (name + VE icon + launcher relaunch) and# pin the window icon explicitly so pythonw.exe art never leaks through.@@ -370,10 +390,9 @@ def launch_desktop() -> int:root_window.frameSwapped.connect(on_first_frame)- if bridge.windowMaximized:- root_window.showMaximized()- else:- root_window.showNormal()+ # Always launch maximized, even when the last session was restored or+ # snapped to one side. Saved geometry still supplies the restore size.+ root_window.showMaximized()mark("window_shown")# Qt re-applies window flags when shown, so restore native chrome once.diff --git a/src/desktop/auto_color.py b/src/desktop/auto_color.pyindex ebb1ba7..518da1a 100644--- a/src/desktop/auto_color.py+++ b/src/desktop/auto_color.py@@ -1,231 +1,356 @@-"""Content-aware starting point for editable LUT color adjustments.--Auto analyzes pixels at the source's native precision. Only the statistics-use a bounded sample; the chosen settings are applied to full-resolution-previews, exports, and saved cubes by the existing grading pipeline.-"""--from __future__ import annotations-+"""Content-aware starting point for editable LUT color adjustments.++Auto analyzes the selected image, timeline frame, or fixed video samples at native precision.+Only the statistics use a bounded sample; the chosen settings are applied to full-resolution+previews, exports, and saved cubes by the existing grading pipeline.+"""++from __future__ import annotations+import mathimport subprocess-from dataclasses import replace-from pathlib import Path-+from dataclasses import replace+from pathlib import Path+import numpy as np-from ..core.jobs import Cancelled-from ..core.paths import FFMPEG-from ..neural_rendering.image.decoder import decode_image-from ..settings.models import DEFAULT_SETTINGS, LUT_ADJUSTMENT_RANGES, UISettings-from .coloring import grade_lut_rgb, load_cube_lut, sample_cube_lut--+from ..core.ffmpeg.probe import probe_video+from ..core.ffmpeg.vulkan import prepare_command+from ..core.jobs import Cancelled+from ..core.paths import FFMPEG+from ..neural_rendering.image.decoder import decode_image+from ..settings.models import DEFAULT_SETTINGS, LUT_ADJUSTMENT_RANGES, UISettings+from .coloring import grade_lut_rgb, load_cube_lut, sample_cube_lut++_LUMA = np.asarray((0.2126, 0.7152, 0.0722), dtype=np.float32)+FIXED_FRAME_COUNT = 15+_FIXED_PIXEL_BUDGET = 220_000+++def _check_cancel(controller) -> None:+ if controller is not None and controller.cancel.is_set():+ raise Cancelled("Automatic color adjustment cancelled.")+++def _clamp(value: float, low: float, high: float) -> float:+ return max(low, min(high, value))+++def _analysis_pixels(rgba: np.ndarray, limit: int) -> np.ndarray:+ """Sample a spatial grid while discarding transparent pixels."""+ height, width = rgba.shape[:2]+ stride = max(1, math.ceil(max(height, width) / 512))+ sampled = rgba[::stride, ::stride].reshape(-1, rgba.shape[-1])+ if len(sampled) > limit:+ sampled = sampled[np.linspace(0, len(sampled) - 1, limit, dtype=np.intp)]+ maximum = float(np.iinfo(rgba.dtype).max)+ if sampled.shape[-1] == 4:+ sampled = sampled[sampled[:, 3] > maximum * 0.05]+ return np.ascontiguousarray(sampled[:, :3].astype(np.float32) / maximum)+++def _video_sample(source: Path, seconds: float, size: tuple[int, int], controller,+ *, frame_exact: bool = False, trim_borders: bool = False) -> np.ndarray | None:+ width, height = size+ scale = min(1.0, 512.0 / max(width, height))+ sample_width = max(1, round(width * scale))+ sample_height = max(1, round(height * scale))+ seek = ["-ss", f"{max(0.0, seconds):.6f}", "-i", str(source)]+ if frame_exact:+ # Match preview extraction: seek to the nominal frame start, with a+ # 2 ms epsilon for rounded timestamps (e.g. 23.976/29.97 fps). A short+ # accurate output seek after the fast pre-seek avoids adjacent frames.+ aligned = max(0.0, seconds - 0.002)+ fast = max(0.0, aligned - 2.0)+ seek = ["-ss", f"{fast:.6f}", "-i", str(source),+ "-ss", f"{aligned - fast:.6f}"]+ command = [str(FFMPEG), "-hide_banner", "-loglevel", "error", *seek,+ "-map", "0:v:0", "-frames:v", "1", "-an", "-vf",+ f"scale={sample_width}:{sample_height}:flags=area",+ "-f", "rawvideo", "-pix_fmt", "rgba64le", "pipe:1"]+ _check_cancel(controller)+ command = prepare_command(command, selection=getattr(controller, "ffmpeg_device", None))+ process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE,+ creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))+ if controller is not None:+ controller.register(process)+ try:+ pixels, _errors = process.communicate(timeout=30)+ _check_cancel(controller)+ if process.returncode != 0 or len(pixels) != sample_width * sample_height * 8:+ return None+ finally:+ if process.poll() is None:+ process.kill()+ process.communicate()+ if controller is not None:+ controller.unregister(process)+ # Vulkan supports four-channel 16-bit textures; packed RGB48 is not a+ # renderable image format on these drivers. Alpha is discarded in analysis.+ rgba = np.frombuffer(pixels, dtype="<u2").reshape(sample_height, sample_width, 4)+ if trim_borders:+ rgba = _trim_black_borders(rgba)+ return _analysis_pixels(rgba, 32_000)-def _check_cancel(controller) -> None:- if controller is not None and controller.cancel.is_set():- raise Cancelled("Automatic color adjustment cancelled.")+def _trim_black_borders(rgba: np.ndarray) -> np.ndarray:+ """Exclude paired, nearly solid black letterbox/pillarbox borders."""+ black = np.max(rgba[..., :3], axis=-1) <= np.iinfo(rgba.dtype).max / 255+ height, width = black.shape+ def extent(lines):+ count = 0+ for value in lines:+ if not value:+ break+ count += 1+ return count-def _clamp(value: float, low: float, high: float) -> float:- return max(low, min(high, value))+ rows = np.mean(black, axis=1) >= .995+ columns = np.mean(black, axis=0) >= .995+ top, bottom = extent(rows), extent(rows[::-1])+ left, right = extent(columns), extent(columns[::-1])+ # Require borders on both sides with similar sizes, and retain most of+ # the picture. A dark scene or one dark edge is not evidence of a border.+ if not (0 < top <= height * .25 and 0 < bottom <= height * .25+ and max(top, bottom) <= min(top, bottom) * 2):+ top = bottom = 0+ if not (0 < left <= width * .25 and 0 < right <= width * .25+ and max(left, right) <= min(left, right) * 2):+ left = right = 0+ return rgba[top:height - bottom, left:width - right]-def _analysis_pixels(rgba: np.ndarray, limit: int) -> np.ndarray:- """Sample a spatial grid while discarding transparent pixels."""- height, width = rgba.shape[:2]- stride = max(1, math.ceil(max(height, width) / 512))- sampled = rgba[::stride, ::stride].reshape(-1, rgba.shape[-1])- if len(sampled) > limit:- sampled = sampled[np.linspace(0, len(sampled) - 1, limit, dtype=np.intp)]- maximum = float(np.iinfo(rgba.dtype).max)- if sampled.shape[-1] == 4:- sampled = sampled[sampled[:, 3] > maximum * 0.05]- return np.ascontiguousarray(sampled[:, :3].astype(np.float32) / maximum)+def _fixed_frame_stamps(duration: float, fps: float = 0.0) -> list[float]:+ """Spread samples across the video interior; short clips use unique frames."""+ if not math.isfinite(duration) or duration <= 0:+ raise ValueError("Video duration is unavailable; reload the input and try Auto again.")+ stamps = np.linspace(duration * .05, duration * .95, FIXED_FRAME_COUNT)+ if math.isfinite(fps) and fps > 0:+ last = max(0, round(duration * fps) - 1)+ stamps = [min(last, math.floor(seconds * fps + 1e-6)) / fps for seconds in stamps]+ return list(dict.fromkeys(float(stamp) for stamp in stamps))-def _video_sample(source: Path, seconds: float, size: tuple[int, int], controller) -> np.ndarray | None:- width, height = size- scale = min(1.0, 512.0 / max(width, height))- sample_width = max(1, round(width * scale))- sample_height = max(1, round(height * scale))- command = [str(FFMPEG), "-hide_banner", "-loglevel", "error",- "-ss", f"{max(0.0, seconds):.6f}", "-i", str(source),- "-frames:v", "1", "-an", "-vf",- f"scale={sample_width}:{sample_height}:flags=area",- "-f", "rawvideo", "-pix_fmt", "rgb48le", "pipe:1"]- _check_cancel(controller)- result = subprocess.run(- command, capture_output=True, timeout=30, check=False,- creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),- )+def _fixed_video_samples(source: Path, duration: float, size: tuple[int, int] | None,+ fps: float, controller, progress) -> list[np.ndarray]:+ if size is None or min(size) < 1:+ raise ValueError("Video dimensions are unavailable; reload the input and try Auto again.")_check_cancel(controller)- if result.returncode != 0 or len(result.stdout) != sample_width * sample_height * 6:- return None- rgb = np.frombuffer(result.stdout, dtype="<u2").reshape(sample_height, sample_width, 3)- return _analysis_pixels(rgb, 32_000)---def _source_pixels(source: Path, mode: str, duration_seconds: float,- video_size: tuple[int, int] | None, controller, progress) -> np.ndarray:- if mode == "Image":- _check_cancel(controller)- pixels = _analysis_pixels(decode_image(source).rgba, 220_000)+ if not math.isfinite(duration) or duration <= 0 or not math.isfinite(fps) or fps <= 0:+ metadata = probe_video(source, count_mode="metadata", controller=controller)+ if not math.isfinite(duration) or duration <= 0:+ duration = float(metadata.get("duration") or 0)+ if not math.isfinite(fps) or fps <= 0:+ fps = float(metadata.get("fps") or 0)+ stamps = _fixed_frame_stamps(duration, fps)+ frames, fallback = [], []+ for index, stamp in enumerate(stamps):_check_cancel(controller)- elif mode == "Video":- if video_size is None or min(video_size) < 1:- raise ValueError("Video dimensions are unavailable; reload the input and try Auto again.")- if duration_seconds > 0:- stamps = [duration_seconds * fraction for fraction in- (0.05, 0.2, 0.35, 0.5, 0.65, 0.8, 0.95)]- else:- stamps = [0.0, 1.0, 3.0, 6.0]- frames = []- fallback_frames = []- for index, stamp in enumerate(stamps):- sample = _video_sample(source, stamp, video_size, controller)- if sample is not None and len(sample):- fallback_frames.append(sample)- luma = sample @ _LUMA- # Ignore nearly black/white transition frames when there are- # other usable frames in the sequence.- if 0.025 < float(np.median(luma)) < 0.975:- frames.append(sample)- if progress is not None:- progress((index + 1) / (len(stamps) + 1), "Analyzing video color")- if not frames:- frames = fallback_frames- if not frames:- raise ValueError("Could not find a usable video frame for Auto color adjustment.")- pixels = np.concatenate(frames, axis=0)- else:- raise ValueError("Auto color adjustment requires an image or video input.")- if len(pixels) < 32:- raise ValueError("The input has too few visible pixels for Auto color adjustment.")- return pixels---def _linear(value: float) -> float:- return value / 12.92 if value <= 0.04045 else ((value + 0.055) / 1.055) ** 2.4+ sample = _video_sample(source, stamp, size, controller, frame_exact=True, trim_borders=True)+ if sample is not None and len(sample) >= 32:+ fallback.append(sample)+ low, high = np.percentile(sample @ _LUMA, (2, 98))+ # Keep low/high-key scenes that contain detail; omit near-blank+ # fades when other usable frames are available.+ if high > .025 and low < .975:+ frames.append(sample)+ if progress is not None:+ progress((index + 1) / (len(stamps) + 1), "Analyzing video color")+ frames = frames or fallback+ if not frames:+ raise ValueError("Could not find a usable video frame for Auto color adjustment.")+ count = min(_FIXED_PIXEL_BUDGET // len(frames), *(len(sample) for sample in frames))+ # Equal contributions prevent full-screen inserts from outweighing+ # letterboxed scenes; keep the total statistics workload bounded.+ return [sample[np.linspace(0, len(sample) - 1, count, dtype=np.intp)] for sample in frames]+def _source_pixels(source: Path, mode: str, duration_seconds: float,+ video_size: tuple[int, int] | None, controller, progress,+ *, video_frame_seconds: float | None = None) -> np.ndarray:+ if mode == "Image":+ _check_cancel(controller)+ pixels = _analysis_pixels(decode_image(source).rgba, 220_000)+ _check_cancel(controller)+ elif mode == "Video":+ if video_size is None or min(video_size) < 1:+ raise ValueError("Video dimensions are unavailable; reload the input and try Auto again.")+ if video_frame_seconds is not None:+ # Auto is local to the selected frame. Never substitute other+ # scenes, even when this frame is a black/white transition.+ stamps = [video_frame_seconds]+ elif duration_seconds > 0:+ stamps = [duration_seconds * fraction for fraction in+ (0.05, 0.2, 0.35, 0.5, 0.65, 0.8, 0.95)]+ else:+ stamps = [0.0, 1.0, 3.0, 6.0]+ frames = []+ fallback_frames = []+ for index, stamp in enumerate(stamps):+ sample = _video_sample(source, stamp, video_size, controller,+ frame_exact=video_frame_seconds is not None)+ if sample is not None and len(sample):+ fallback_frames.append(sample)+ luma = sample @ _LUMA+ # Ignore nearly black/white transition frames when there are+ # other usable frames in the sequence.+ if 0.025 < float(np.median(luma)) < 0.975:+ frames.append(sample)+ if progress is not None:+ progress((index + 1) / (len(stamps) + 1), "Analyzing video color")+ if not frames:+ frames = fallback_frames+ if not frames:+ raise ValueError("Could not find a usable video frame for Auto color adjustment.")+ pixels = np.concatenate(frames, axis=0)+ else:+ raise ValueError("Auto color adjustment requires an image or video input.")+ if len(pixels) < 32:+ raise ValueError("The input has too few visible pixels for Auto color adjustment.")+ return pixels+++def _linear(value: float) -> float:+ return value / 12.92 if value <= 0.04045 else ((value + 0.055) / 1.055) ** 2.4++def recommend_lut_adjustments(identity: np.ndarray, sampled: np.ndarray,*, allow_white_balance: bool = True,- hdr: bool = False) -> dict[str, int | float]:- """Choose a restrained grade from robust tone and neutral-color statistics.-- A universal "best" look cannot be inferred from pixels alone, so Auto- favors highlight protection, modest contrast, and minimal color shifts.- All returned controls remain editable by the user.- """- if identity.shape != sampled.shape or identity.ndim != 2 or identity.shape[1] != 3:- raise ValueError("Auto color analysis requires matching RGB samples.")+ hdr: bool = False, frame_count: int = 1,+ controller=None) -> dict[str, int | float]:+ """Choose a restrained grade from robust tone and neutral-color statistics.++ A universal "best" look cannot be inferred from pixels alone, so Auto+ favors highlight protection, modest contrast, and minimal color shifts.+ All returned controls remain editable by the user.+ """+ if identity.shape != sampled.shape or identity.ndim != 2 or identity.shape[1] != 3:+ raise ValueError("Auto color analysis requires matching RGB samples.")+ _check_cancel(controller)+ frame_count = max(1, int(frame_count))valid = np.all(np.isfinite(identity) & np.isfinite(sampled), axis=1)- identity = np.clip(identity[valid], 0.0, 1.0)- sampled = np.clip(sampled[valid], 0.0, 1.0)- if len(identity) < 32:- raise ValueError("The input has too few valid colors for Auto adjustment.")-- luma = sampled @ _LUMA- p02, p10, p50, p90, p95, p98, p99 = np.percentile(- luma, (2, 10, 50, 90, 95, 98, 99))- if p98 - p02 < 0.06:- # A blank/faded frame gives no reliable evidence of the intended look.- return {key: getattr(DEFAULT_SETTINGS, key) for key in LUT_ADJUSTMENT_RANGES}- exposure = 0.55 * math.log2(_linear(0.82) / max(_linear(float(p95)), 0.003))- exposure = _clamp(exposure, -0.7, 1.2)- if p99 > 0.75:- highlight_limit = 0.8 * math.log2(_linear(0.98) / max(_linear(float(p99)), 0.003))- exposure = min(exposure, highlight_limit)- if p50 < 0.22 and p99 > 0.7:- exposure = min(exposure, 0.25) # Preserve low-key scenes with bright accents.- if p50 > 0.72 and p02 > 0.2:- exposure = max(exposure, -0.25) # Preserve a deliberate high-key scene.- if hdr:- exposure = _clamp(exposure, -0.25, 0.25)- exposure = round(round(_clamp(exposure, -3.0, 3.0) / 0.05) * 0.05, 2)-- base_settings = replace(DEFAULT_SETTINGS, lut_exposure=exposure)- exposed = grade_lut_rgb(sampled, sampled, base_settings)- exposed_luma = exposed @ _LUMA- e02, e10, e50, e90, e95, e98, e99 = np.percentile(- exposed_luma, (2, 10, 50, 90, 95, 98, 99))- contrast = round(_clamp((0.64 / max(float(e90 - e10), 0.15) - 1.0) * 20.0, -12, 20))- shadows = round(_clamp((0.13 - float(e10)) * 115, 0, 18))- highlights = -round(_clamp((float(e99) - 0.92) * 140, 0, 25))- whites = round(_clamp((0.86 - float(e98)) * 60, 0, 12))- blacks = -round(_clamp((float(e02) - 0.05) * 130, 0, 18))- midtones = round(_clamp((0.30 - float(e50)) * 45, 0, 10)) if e99 > 0.7 else 0-- temperature = tint = 0- if allow_white_balance:- chroma = np.ptp(sampled, axis=1)- neutral = (chroma < 0.055) & (luma > 0.18) & (luma < 0.88)- if np.count_nonzero(neutral) >= max(100, int(len(sampled) * 0.02)):- r, g, b = np.median(sampled[neutral], axis=0)- level = max(float((r + g + b) / 3), 0.1)- temperature = round(_clamp(float(b - r) / level * 125, -16, 16))- tint = round(_clamp(float(g - (r + b) * 0.5) / level * 220, -12, 12))-- chroma = np.ptp(sampled, axis=1)- medium = chroma[(luma > 0.12) & (luma < 0.9)]- mean_chroma = float(np.mean(medium)) if len(medium) else 0.0- vibrance = (round(_clamp((0.2 - mean_chroma) * 75, 0, 16))- if mean_chroma > 0.035 else 0)- saturation = -round(_clamp((mean_chroma - 0.4) * 30, 0, 8))+ if not np.all(valid) or len(identity) % frame_count:+ frame_count = 1+ identity = np.clip(identity[valid], 0.0, 1.0)+ sampled = np.clip(sampled[valid], 0.0, 1.0)+ if len(identity) < 32:+ raise ValueError("The input has too few valid colors for Auto adjustment.")++ luma = sampled @ _LUMA+ p02, p10, p50, p90, p95, p98, p99 = np.percentile(+ luma, (2, 10, 50, 90, 95, 98, 99))+ if p98 - p02 < 0.06:+ # A blank/faded frame gives no reliable evidence of the intended look.+ return {key: getattr(DEFAULT_SETTINGS, key) for key in LUT_ADJUSTMENT_RANGES}+ exposure = 0.55 * math.log2(_linear(0.82) / max(_linear(float(p95)), 0.003))+ exposure = _clamp(exposure, -0.7, 1.2)+ if p99 > 0.75:+ highlight_limit = 0.8 * math.log2(_linear(0.98) / max(_linear(float(p99)), 0.003))+ exposure = min(exposure, highlight_limit)+ if p50 < 0.22 and p99 > 0.7:+ exposure = min(exposure, 0.25) # Preserve low-key scenes with bright accents.+ if p50 > 0.72 and p02 > 0.2:+ exposure = max(exposure, -0.25) # Preserve a deliberate high-key scene.+ if hdr:+ exposure = _clamp(exposure, -0.25, 0.25)+ exposure = round(round(_clamp(exposure, -3.0, 3.0) / 0.05) * 0.05, 2)++ base_settings = replace(DEFAULT_SETTINGS, lut_exposure=exposure)+ exposed = grade_lut_rgb(sampled, sampled, base_settings)+ exposed_luma = exposed @ _LUMA+ e02, e10, e50, e90, e95, e98, e99 = np.percentile(+ exposed_luma, (2, 10, 50, 90, 95, 98, 99))+ contrast = round(_clamp((0.64 / max(float(e90 - e10), 0.15) - 1.0) * 20.0, -12, 20))+ shadows = round(_clamp((0.13 - float(e10)) * 115, 0, 18))+ highlights = -round(_clamp((float(e99) - 0.92) * 140, 0, 25))+ whites = round(_clamp((0.86 - float(e98)) * 60, 0, 12))+ blacks = -round(_clamp((float(e02) - 0.05) * 130, 0, 18))+ midtones = round(_clamp((0.30 - float(e50)) * 45, 0, 10)) if e99 > 0.7 else 0++ temperature = tint = 0+ if allow_white_balance:+ chroma = np.ptp(sampled, axis=1)+ neutral = (chroma < 0.055) & (luma > 0.18) & (luma < 0.88)+ if np.count_nonzero(neutral) >= max(100, int(len(sampled) * 0.02)):+ r, g, b = np.median(sampled[neutral], axis=0)+ level = max(float((r + g + b) / 3), 0.1)+ temperature = round(_clamp(float(b - r) / level * 125, -16, 16))+ tint = round(_clamp(float(g - (r + b) * 0.5) / level * 220, -12, 12))++ chroma = np.ptp(sampled, axis=1)+ medium = chroma[(luma > 0.12) & (luma < 0.9)]+ mean_chroma = float(np.mean(medium)) if len(medium) else 0.0+ vibrance = (round(_clamp((0.2 - mean_chroma) * 75, 0, 16))+ if mean_chroma > 0.035 else 0)+ saturation = -round(_clamp((mean_chroma - 0.4) * 30, 0, 8))++ values: dict[str, int | float] = {key: getattr(DEFAULT_SETTINGS, key)+ for key in LUT_ADJUSTMENT_RANGES}+ values.update(lut_mix=100, lut_exposure=exposure, lut_contrast=contrast,+ lut_highlights=highlights, lut_shadows=shadows,+ lut_whites=whites, lut_blacks=blacks, lut_midtones=midtones,+ lut_temperature=temperature, lut_tint=tint,+ lut_vibrance=vibrance, lut_saturation=saturation)++ # Reject a newly clipped look. Existing clipped highlights cannot be+ # recovered, but Auto must not substantially add to them.+ def clipping_rates(rgb):+ white = np.any(rgb >= .997, axis=1).reshape(frame_count, -1).mean(axis=1)+ black = np.all(rgb <= .003, axis=1).reshape(frame_count, -1).mean(axis=1)+ return white, black- values: dict[str, int | float] = {key: getattr(DEFAULT_SETTINGS, key)- for key in LUT_ADJUSTMENT_RANGES}- values.update(lut_mix=100, lut_exposure=exposure, lut_contrast=contrast,- lut_highlights=highlights, lut_shadows=shadows,- lut_whites=whites, lut_blacks=blacks, lut_midtones=midtones,- lut_temperature=temperature, lut_tint=tint,- lut_vibrance=vibrance, lut_saturation=saturation)-- # Reject a newly clipped look. Existing clipped highlights cannot be- # recovered, but Auto must not substantially add to them.- baseline_white = float(np.mean(np.any(sampled >= 0.997, axis=1)))- baseline_black = float(np.mean(np.all(sampled <= 0.003, axis=1)))- for _ in range(8):- graded = grade_lut_rgb(identity, sampled, replace(DEFAULT_SETTINGS, **values))- white = float(np.mean(np.any(graded >= 0.997, axis=1)))- black = float(np.mean(np.all(graded <= 0.003, axis=1)))- if white <= baseline_white + 0.012 and black <= baseline_black + 0.012:+ baseline_white, baseline_black = clipping_rates(sampled)+ for _ in range(32 if frame_count > 1 else 8):+ _check_cancel(controller)+ graded = grade_lut_rgb(identity, sampled, replace(DEFAULT_SETTINGS, **values))+ white, black = clipping_rates(graded)+ if np.all(white <= baseline_white + .012) and np.all(black <= baseline_black + .012):break- if white > baseline_white + 0.012:- if values["lut_whites"] > 0:- values["lut_whites"] = max(0, int(values["lut_whites"]) - 3)- elif values["lut_exposure"] > 0:- values["lut_exposure"] = round(max(0.0, float(values["lut_exposure"]) - 0.05), 2)- else:- values["lut_highlights"] = max(-35, int(values["lut_highlights"]) - 4)- if black > baseline_black + 0.012:- values["lut_blacks"] = min(0, int(values["lut_blacks"]) + 3)- values["lut_contrast"] = max(-12, int(values["lut_contrast"]) - 2)- return values--+ if np.any(white > baseline_white + .012):+ if values["lut_whites"] > 0:+ values["lut_whites"] = max(0, int(values["lut_whites"]) - 3)+ elif values["lut_exposure"] > 0:+ values["lut_exposure"] = round(max(0.0, float(values["lut_exposure"]) - 0.05), 2)+ else:+ values["lut_highlights"] = max(-35, int(values["lut_highlights"]) - 4)+ if np.any(black > baseline_black + .012):+ values["lut_blacks"] = min(0, int(values["lut_blacks"]) + 3)+ values["lut_contrast"] = max(-12, int(values["lut_contrast"]) - 2)+ return values++def analyze_color_source(source: str | Path, settings: UISettings, mode: str, *,duration_seconds: float = 0.0,video_size: tuple[int, int] | None = None,- hdr: bool = False, controller=None, progress=None) -> dict[str, int | float]:- """Analyze the selected source and return editable Color Adjustment values."""+ video_frame_seconds: float | None = 0.0,+ video_fps: float = 0.0,+ hdr: bool = False, controller=None, progress=None) -> dict[str, int | float]:+ """Analyze the image, one frame, or fixed video samples (time=None)."""path = Path(source).resolve()- pixels = _source_pixels(path, mode, duration_seconds, video_size, controller, progress)- _check_cancel(controller)- if settings.lut_path:- lut = load_cube_lut(settings.lut_path)- sampled = np.empty_like(pixels)- for offset in range(0, len(pixels), 65_536):- _check_cancel(controller)- end = min(len(pixels), offset + 65_536)- sampled[offset:end] = sample_cube_lut(pixels[offset:end], lut)+ frame_count = 1+ if mode == "Video" and video_frame_seconds is None:+ frames = _fixed_video_samples(path, duration_seconds, video_size, video_fps, controller, progress)+ frame_count = len(frames)+ pixels = np.concatenate(frames, axis=0)else:- sampled = pixels+ pixels = _source_pixels(path, mode, duration_seconds, video_size, controller, progress,+ video_frame_seconds=video_frame_seconds)+ _check_cancel(controller)+ if settings.lut_path:+ lut = load_cube_lut(settings.lut_path)+ sampled = np.empty_like(pixels)+ for offset in range(0, len(pixels), 65_536):+ _check_cancel(controller)+ end = min(len(pixels), offset + 65_536)+ sampled[offset:end] = sample_cube_lut(pixels[offset:end], lut)+ else:+ sampled = pixelsvalues = recommend_lut_adjustments(pixels, sampled,- allow_white_balance=not (settings.lut_path or hdr), hdr=hdr)- if progress is not None:- progress(1.0, "Auto color adjustment ready")- return values+ allow_white_balance=not (settings.lut_path or hdr), hdr=hdr,+ frame_count=frame_count, controller=controller)+ _check_cancel(controller)+ if progress is not None:+ progress(1.0, "Auto color adjustment ready")+ return valuesdiff --git a/src/desktop/bridge.py b/src/desktop/bridge.pyindex aeec991..3325fa6 100644--- a/src/desktop/bridge.py+++ b/src/desktop/bridge.py@@ -10,7 +10,6 @@ import mathimport hashlibimport importlibimport shutil-import tempfileimport urllib.parseimport urllib.requestfrom pathlib import Path@@ -20,17 +19,18 @@ from typing import Anyfrom PySide6.QtCore import QObject, QThreadPool, QTimer, QUrl, Signal, Slot, Property, QSettings, qVersion, QBuffer, QIODevicefrom PySide6.QtGui import QGuiApplication, QImage, QPixmap-from ..core.paths import ROOT, CONFIG_PATH, OUTPUTS, LOGS, FFMPEG, FFPROBE, MPV, APP_TEMP+from ..core.paths import ROOT, CONFIG_PATH, OUTPUTS, LOGS, FFMPEG, FFPROBE, MPV, APP_TEMP, UI_SETTINGS_PATH+from ..portable import decode_app_path, encode_app_pathfrom ..core.disk_paths import prepare_output_dir, supported_file as _is_supported_media_filefrom ..core.cache_cleanup import cleanup_old_cachesfrom ..core import app_logfrom ..core.runtime import prepare_runtime, NR_STYLES, UPSCALING_MODES, resolve_upscaling_mode, resolve_output_sizefrom ..core.dlss_modes import DLSS_MODES, DLSS_PRESETS, UPSCALE_ENGINES, dlss_output_size-from ..core.ffmpeg import CODEC_CHOICES, ENCODING_QUALITIES, FIXED_QUALITY_CODECS, container_for_codec, hdr_mode_supported, probe_video+from ..core.ffmpeg import CODEC_CHOICES, ENCODING_QUALITIES, FIXED_QUALITY_CODECS, container_for_codec, containers_for_codec, hdr_mode_supported, probe_video, resolve_containerfrom ..core.naming import RENAME_MODES, validate_renamefrom ..core.nr_composition import inspect_nr_mask, mask_statusfrom ..settings.models import (- CONTAINER_CHOICES, DEFAULT_SETTINGS, PREVIEW_ENCODING_CHOICES, UPSCALE_MODE_CHOICES,+ DEFAULT_SETTINGS, UPSCALE_MODE_CHOICES,UPSCALE_PREVIEW_LENGTH_CHOICES, UISettings, IMAGE_STAGE_ORDER, VIDEO_STAGE_ORDER,IMAGE_SCALING_FILTERS, VIDEO_SCALING_FILTERS, IMAGE_16BIT_FORMATS,LUT_ADJUSTMENT_RANGES, LUT_RESOLUTIONS, SHARPENING_METHODS,@@ -40,14 +40,17 @@ from ..settings.storage import SETTINGS_STATE, load_settings, save_settingsfrom ..settings.presets import export_settings_preset, export_settings_preset_to, import_settings_presetfrom .models import BatchListModel+from .i18n import DEFAULT_LANGUAGE, LANGUAGE_CODES, LanguageManager, language_choices, UiMessage, translate_text, join_messagesfrom .image_provider import PreviewImageProviderfrom .coloring import load_cube_lut, save_cube_lutfrom .auto_color import analyze_color_source+from .reference_color import analyze_color_referencefrom .color_preview import (FastPreviewUnavailable, MAX_PREVIEW_PIXELS,render_color_still_preview)from .workers import JobWorker-from .workflow import (enabled_stages, estimate_pipeline, preflight_source,+from .workflow import (enabled_stages, estimate_pipeline, preflight_source, preview_settings_key,render_pipeline_batch, render_pipeline_preview)+from .preview_cache import cache_key, optional_file_identityfrom .state import (PreviewState, IDLE, SCANNING_INPUTS, LOADING_METADATA, PREVIEW_PREPARING,PREVIEW_RUNNING, PREVIEW_CANCELLING, BATCH_PREPARING, BATCH_RUNNING,@@ -144,7 +147,14 @@ class AppBridge(QObject):"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"}+ LIVE_RESTART_FIELDS = {"ai_gpu_uuid", "video_gpu_uuid", "ffmpeg_device", "live_upscaling_factor"}++ VIDEO_EXPORT_FIELDS = {+ "codec", "container", "quality", "hdr_mode",+ "upscale_codec", "upscale_container", "upscale_quality",+ "frame_interpolation_codec", "frame_interpolation_container",+ "frame_interpolation_quality", "frame_interpolation_hdr_mode",+ }# FI settings that invalidate pre-rendered timeline ranges. A tweak# here makes existing green spans stale, so they are cleared. Rename /@@ -152,9 +162,8 @@ class AppBridge(QObject):# (older spans remain valid footage for their range). Realtime preview# stays disabled for Frame Interpolation regardless (manual Preview only).FI_RANGE_FIELDS = {+ "ffmpeg_device", "ai_gpu_uuid", "video_gpu_uuid","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.PREVIEW_RANGE_LIMIT = 32@@ -164,8 +173,9 @@ class AppBridge(QObject):# selected item when Realtime Preview is enabled. Rename/output-only# settings are intentionally excluded so they do not waste GPU work.AUTO_PREVIEW_FIELDS = {+ "ffmpeg_device","image_stage_order", "video_stage_order", "image_enabled_stages", "video_enabled_stages",- "denoise_strength", "denoise_deblock", "denoise_temporal", "cas_sharpness", "sharpening_method",+ "cas_sharpness", "sharpening_method","coloring_mode", "color_match_source", "color_match_reference", "lut_path","ai_gpu_uuid", "video_gpu_uuid","nr_style", "nr_intensity", "nr_passes",@@ -178,7 +188,6 @@ class AppBridge(QObject):"nr_scale_method", "nr_dlss_mode", "nr_dlss_preset","upscale_image_engine", "upscale_image_dlss_mode", "upscale_image_dlss_preset","upscale_engine", "upscale_dlss_mode", "upscale_dlss_preset",- "preview_encoding","upscale_image_vsr_quality", "upscale_image_size_mode","upscale_image_scale_factor", "upscale_image_width","upscale_image_height", "upscale_image_aspect_lock",@@ -188,15 +197,11 @@ class AppBridge(QObject):"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",} | set(LUT_ADJUSTMENT_RANGES) | {"lut_resolution"}PROCESSING_PREVIEW_FIELDS = {"nr-image": {- "denoise_strength", "denoise_deblock", "cas_sharpness", "sharpening_method",+ "cas_sharpness", "sharpening_method","image_scaling_filter", "upscaling_factor","coloring_mode", "color_match_source", "color_match_reference", "lut_path","upscale_image_dlss_mode", "upscale_image_dlss_preset",@@ -205,7 +210,7 @@ class AppBridge(QObject):"upscale_image_height", "upscale_image_aspect_lock",} | set(LUT_ADJUSTMENT_RANGES) | {"lut_resolution"},"nr-video": {- "denoise_strength", "denoise_deblock", "denoise_temporal", "cas_sharpness", "sharpening_method",+ "cas_sharpness", "sharpening_method","video_scaling_filter", "upscaling_factor","lut_path","upscale_dlss_mode", "upscale_dlss_preset",@@ -219,24 +224,25 @@ class AppBridge(QObject):"upscale-video": {"upscale_engine", "upscale_dlss_mode", "upscale_dlss_preset"},}UPSCALE_RANGE_FIELDS = {+ "ffmpeg_device","upscale_engine", "upscale_dlss_mode", "upscale_dlss_preset",- "ai_gpu_uuid", "video_gpu_uuid", "preview_encoding",+ "ai_gpu_uuid", "video_gpu_uuid","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",}# Neural Rendering settings that invalidate pre-rendered timeline spans.# The manual clip length itself is excluded (older spans remain valid# footage for their range), mirroring FI/upscale.NR_RANGE_FIELDS = {+ "ffmpeg_device","video_stage_order", "video_enabled_stages",- "denoise_strength", "denoise_deblock", "denoise_temporal", "cas_sharpness", "sharpening_method",+ "cas_sharpness", "sharpening_method","nr_scale_method", "nr_dlss_mode", "nr_dlss_preset",- "ai_gpu_uuid", "video_gpu_uuid", "preview_encoding",+ "ai_gpu_uuid", "video_gpu_uuid","nr_style", "nr_intensity", "nr_passes","local_tone_strength", "local_structure_strength","skin_structure_strength", "automatic_mask",@@ -244,7 +250,7 @@ class AppBridge(QObject):"face_skin_protection", "grain_preservation","shimmer_suppression", "mask_feather", "nr_mask","lut_path",- "upscaling_factor", "video_scaling_filter", "codec", "quality", "hdr_mode",+ "upscaling_factor", "video_scaling_filter",} | set(LUT_ADJUSTMENT_RANGES) | {"lut_resolution"}# UI State Signals@@ -285,11 +291,15 @@ class AppBridge(QObject):isLiveStartingChanged = Signal()liveTelemetryChanged = Signal()autoPreviewChanged = Signal()+ previewBusyChanged = Signal()+ languageChanged = Signal()lutSaveChanged = Signal()lutAutoChanged = Signal()+ lutReferenceChanged = Signal()def __init__(self, image_provider: PreviewImageProvider, parent: Any = None) -> None:super().__init__(parent)+ self.operationStateChanged.connect(self.previewBusyChanged)self._image_provider = image_providerself._thread_pool = QThreadPool.globalInstance()self._active_worker: JobWorker | None = None@@ -297,8 +307,12 @@ class AppBridge(QObject):self._live_worker: JobWorker | None = Noneself._scan_worker: JobWorker | None = Noneself._metadata_worker: JobWorker | None = None+ self._queue_metadata_workers: dict[str, JobWorker] = {}self._lut_save_worker: JobWorker | None = Noneself._lut_auto_worker: JobWorker | None = None+ self._lut_auto_mode = ""+ self._lut_reference_worker: JobWorker | None = None+ self._lut_reference_status = ""self._lut_save_status = ""self._operation_state = IDLEself._operation_id = 0@@ -324,10 +338,10 @@ class AppBridge(QObject):# per workflow context and projected through the public properties below.self._is_processing = Falseself._overall_progress = 0.0- self._status_message = "Initializing runtime…"+ self._status_message = UiMessage("Initializing runtime…")self._split_position = 0.5self._preset_status = ""- self._live_status_text = "Idle. Enter a source and press Start Live."+ self._live_status_text = UiMessage("Idle. Enter a source and press Start Live.")self._is_live_running = Falseself._is_live_starting = Falseself._preview_generation = 0@@ -386,25 +400,20 @@ class AppBridge(QObject):self._runtime_error = ""self._startup_warnings: list[str] = []- # 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+ # Desktop layout and dialog choices travel with the application folder.+ # Use the explicit INI constructor: organization/application QSettings+ # would use the Windows registry even if a default format were set.+ UI_SETTINGS_PATH.parent.mkdir(parents=True, exist_ok=True)+ self._ui_settings = QSettings(str(UI_SETTINGS_PATH), QSettings.IniFormat)self._auto_preview_enabled = str(self._ui_settings.value("preview/realtimeEnabled", "true")).lower() in {"1", "true", "yes", "on"}+ self._language_manager = LanguageManager(str(+ self._ui_settings.value("interface/language", DEFAULT_LANGUAGE)+ ))self._auto_preview_pending = Falseself._inspector_width = int(self._ui_settings.value("layout/inspectorWidth", 400))- self._queue_height = int(self._ui_settings.value("layout/queueHeight", 190))+ self._queue_height = max(180, min(720, int(self._ui_settings.value("layout/queueHeight", 330))))self._log_height = int(self._ui_settings.value("layout/logHeight", 220))self._focus_preview = Falseself._window_width = int(self._ui_settings.value("window/width", 1440))@@ -417,7 +426,7 @@ class AppBridge(QObject):# folder paths never leak into shared preset files._export_mode = str(self._ui_settings.value("export/destinationMode", "output"))self._export_destination_mode = _export_mode if _export_mode in {"input", "output", "folder"} else "output"- self._export_folder = str(self._ui_settings.value("export/folder", "") or "")+ self._export_folder = decode_app_path(str(self._ui_settings.value("export/folder", "") or ""))self._auto_preview_timer = QTimer(self)self._auto_preview_timer.setSingleShot(True)@@ -432,7 +441,7 @@ class AppBridge(QObject):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"+ self._preview_cache = APP_TEMP / "native-preview"try:shutil.rmtree(self._preview_cache, ignore_errors=True)self._preview_cache.mkdir(parents=True, exist_ok=True)@@ -492,6 +501,15 @@ class AppBridge(QObject):self.isProcessingChanged.emit()return self._operation_id+ def _set_preview_error(self, message: str, context_key: str | None = None) -> None:+ key = context_key or self._context_key()+ context = self._contexts[key]+ if context.preview_error == message:+ return+ context.preview_error = message+ if key == self._context_key():+ self.mediaPreviewChanged.emit()+def _finish_operation(self, operation_id: int, message: str | None = None) -> bool:if operation_id != self._operation_id or self._shutting_down:return False@@ -512,7 +530,7 @@ class AppBridge(QObject):return self._preview_generationdef _fi_preview_length_seconds(self) -> float:- """Selected FI preview clip length in seconds (3/5/10/20/30)."""+ """Selected FI preview clip length in seconds."""try:length = float(self._settings.frame_interpolation_preview_length)except (TypeError, ValueError):@@ -528,7 +546,7 @@ class AppBridge(QObject):return 3.0def _nr_preview_length_seconds(self) -> float:- """Selected Neural Rendering preview clip length in seconds (3/5/10/20/30)."""+ """Selected Neural Rendering preview clip length in seconds."""selected = self._settings.nr_preview_lengthtry:return float(selected) if selected in PREVIEW_LENGTH_CHOICES else 3.0@@ -606,6 +624,7 @@ class AppBridge(QObject):if self._active_tab != tab:self._active_tab = tabself.activeTabChanged.emit()+ self.operationStateChanged.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@@ -615,7 +634,8 @@ class AppBridge(QObject):except Exception:passself._emit_context()- self._schedule_auto_preview(180)+ if not self._load_active_selection_if_needed():+ self._schedule_auto_preview(180)@Property(str, notify=nrModeChanged)def nrMode(self) -> str:@@ -629,8 +649,10 @@ class AppBridge(QObject):self._nr_mode = modeself.nrModeChanged.emit()self.workflowStagesChanged.emit()+ self.operationStateChanged.emit()self._emit_context()- self._schedule_auto_preview(180)+ if not getattr(self, "_import_switching_mode", False) and not self._load_active_selection_if_needed():+ self._schedule_auto_preview(180)@Property(list, notify=workflowStagesChanged)def workflowStages(self) -> list[dict[str, object]]:@@ -638,33 +660,32 @@ class AppBridge(QObject):enabled = self._settings.image_enabled_stages if self._nr_mode == "Image" else self._settings.video_enabled_stagesreturn [{"id": stage, "enabled": stage in enabled} for stage in order]- @Property(int, notify=settingsUpdated)- def denoiseStrength(self) -> int:- return self._settings.denoise_strength-- @denoiseStrength.setter- def denoiseStrength(self, value: int) -> None:- self._save_setting(denoise_strength=int(value))-- @Property(bool, notify=settingsUpdated)- def denoiseDeblock(self) -> bool:- return self._settings.denoise_deblock+ @Property(list, constant=True)+ def sharpeningMethodChoices(self) -> list[str]:+ return list(SHARPENING_METHODS)- @denoiseDeblock.setter- def denoiseDeblock(self, value: bool) -> None:- self._save_setting(denoise_deblock=bool(value))+ @Property(list, notify=gpuChoicesChanged)+ def ffmpegDeviceChoices(self) -> list[dict[str, str]]:+ from ..core.ffmpeg.vulkan import device_choices+ return device_choices()- @Property(int, notify=settingsUpdated)- def denoiseTemporal(self) -> int:- return self._settings.denoise_temporal+ @Property(str, notify=settingsUpdated)+ def ffmpegDevice(self) -> str:+ return self._settings.ffmpeg_device- @denoiseTemporal.setter- def denoiseTemporal(self, value: int) -> None:- self._save_setting(denoise_temporal=int(value))+ @ffmpegDevice.setter+ def ffmpegDevice(self, value: str) -> None:+ self._save_setting(ffmpeg_device=value)- @Property(list, constant=True)- def sharpeningMethodChoices(self) -> list[str]:- return list(SHARPENING_METHODS)+ @Property(str, notify=settingsUpdated)+ def ffmpegDeviceStatus(self) -> str:+ from ..core.ffmpeg.vulkan import filter_device+ try:+ device = filter_device(self._settings.ffmpeg_device)+ codecs = "Software codecs" if self._settings.ffmpeg_device == "cpu" else "Vulkan codecs where supported; software fallback"+ return f"{codecs}. GPU filters: {device.name}."+ except (ValueError, RuntimeError) as exc:+ return str(exc)@Property(str, notify=settingsUpdated)def sharpeningMethod(self) -> str:@@ -684,8 +705,8 @@ class AppBridge(QObject):@Property(list, constant=True)def coloringModeChoices(self) -> list[dict[str, str]]:- return [{"label": "Match Colors", "value": "Color Match"},- {"label": "Apply LUT", "value": "LUT"}]+ return [{"label": "Apply LUT", "value": "LUT"},+ {"label": "Match Colors", "value": "Color Match"}]@Property(str, notify=settingsUpdated)def coloringMode(self) -> str:@@ -716,7 +737,7 @@ class AppBridge(QObject):def setColorMatchReference(self, file_url_or_path: str) -> None:path = self._clean_path(file_url_or_path)if path and (Path(path).suffix.lower() not in IMAGE_SUFFIXES or not Path(path).is_file()):- self._status_message = "Choose an existing reference image for Match Colors."+ self._status_message = UiMessage("Choose an existing reference image for Match Colors.")self.statusMessageChanged.emit()self.settingsUpdated.emit()return@@ -764,61 +785,98 @@ class AppBridge(QObject):@Slot()def resetLutAdjustments(self) -> None:- values = {key: getattr(DEFAULT_SETTINGS, key) for key in LUT_ADJUSTMENT_RANGES}- values["lut_resolution"] = DEFAULT_SETTINGS.lut_resolution+ values = {key: getattr(DEFAULT_SETTINGS, key) for key in LUT_ADJUSTMENT_RANGES+ if key != "lut_mix"}self._save_setting(**values)@Property(bool, notify=lutAutoChanged)def lutAutoBusy(self) -> bool:- return self._lut_auto_worker is not None+ return getattr(self, "_lut_auto_worker", None) is not None++ @Property(str, notify=lutAutoChanged)+ def lutAutoMode(self) -> str:+ return getattr(self, "_lut_auto_mode", "")def _finish_lut_auto(self, worker: JobWorker, message: str) -> None:if self._lut_auto_worker is not worker:returnself._lut_auto_worker = None+ self._lut_auto_mode = ""self.lutAutoChanged.emit()+ self.operationStateChanged.emit()if self._shutting_down:returnself._status_message = messageself.statusMessageChanged.emit()self._log(message)+ if self.canPreview and self._auto_preview_enabled:+ self._schedule_auto_preview(90)++ @Slot()+ @Slot(float)+ def autoAdjustLut(self, position_ms: float | None = None) -> None:+ self._start_lut_auto(position_ms)@Slot()- def autoAdjustLut(self) -> None:- if self._lut_auto_worker is not None or self._shutting_down:+ def autoAdjustLutFixedFrames(self) -> None:+ self._start_lut_auto(fixed_frames=True)++ def _start_lut_auto(self, position_ms: float | None = None, *, fixed_frames: bool = False) -> None:+ if self._lut_auto_worker is not None or self._lut_reference_worker is not None or self._shutting_down:returnif self._active_tab != "neural-rendering" or self._operation_state != IDLE:returncontext_key = self._context_key()mode = "Image" if context_key == "nr-image" else "Video"+ if fixed_frames and mode != "Video":+ returnif mode == "Image" and self._settings.coloring_mode != "LUT":returnsource = self._queue_for_context(context_key).selected_path()if not source or not Path(source).is_file():- self._status_message = "Select an image or video before using Auto color."+ self._status_message = UiMessage("Select an image or video before using Auto color.")self.statusMessageChanged.emit()return+ # A pending preview of the previous grade must not advance the input+ # generation while Auto is analyzing. The new grade renders on finish.+ self._auto_preview_pending = False+ self._auto_preview_timer.stop()+ self._scrub_pending_pos = None+ self._scrub_preview_timer.stop()snapshot = self._settingscontext = self._contexts[context_key]+ frame_seconds, frame_index = 0.0, 0+ if mode == "Video" and not fixed_frames:+ if position_ms is not None:+ self.notePlayheadMs(position_ms)+ frame_seconds, frame_index = self._quantize_playhead(context.last_playhead_seconds * 1000.0)source_path = os.path.normcase(os.path.abspath(source))+ source_identity = self._color_file_identity(source)+ lut_identity = self._color_file_identity(snapshot.lut_path)generation = context.generationworker = JobWorker(analyze_color_source, source, snapshot, mode,duration_seconds=context.duration_seconds,video_size=(context.source_width, context.source_height) if mode == "Video" else None,+ video_frame_seconds=None if fixed_frames else frame_seconds,+ video_fps=context.source_fps,hdr=context.source_hdr,)self._lut_auto_worker = worker+ self._lut_auto_mode = "fixed" if fixed_frames else "frame"self.lutAutoChanged.emit()- self._status_message = f"Analyzing {mode.lower()} color…"+ self.operationStateChanged.emit()+ self._status_message = UiMessage("Analyzing %1 color…", UiMessage(mode.lower()))self.statusMessageChanged.emit()def finished(values: dict[str, int | float]) -> None:if self._lut_auto_worker is not worker:returnself._lut_auto_worker = None+ self._lut_auto_mode = ""self.lutAutoChanged.emit()+ self.operationStateChanged.emit()if self._shutting_down:returncurrent_source = self._queue_for_context(context_key).selected_path() or ""@@ -827,14 +885,20 @@ class AppBridge(QObject):and all(getattr(self._settings, key) == getattr(snapshot, key)for key in LUT_ADJUSTMENT_RANGES))if (self._context_key() != context_key or self._active_tab != "neural-rendering"- or self._contexts[context_key].generation != generation- or current_source != source_path or not controls_unchanged):- self._status_message = "Auto color skipped because the input or color controls changed."+ or (not fixed_frames and self._contexts[context_key].generation != generation)+ or (mode == "Video" and not fixed_frames and self._quantize_playhead(+ context.last_playhead_seconds * 1000.0)[1] != frame_index)+ or current_source != source_path or not controls_unchanged+ or self._color_file_identity(source) != source_identity+ or self._color_file_identity(snapshot.lut_path) != lut_identity):+ self._status_message = UiMessage("Auto color skipped because the input or color controls changed.")self.statusMessageChanged.emit()+ if self.canPreview and self._auto_preview_enabled:+ self._schedule_auto_preview(90)returnif not self._save_setting(**values):return- self._status_message = "Auto color adjustments applied. You can fine-tune every slider."+ self._status_message = UiMessage("Auto color adjustments applied. You can fine-tune every slider.")self.statusMessageChanged.emit()self._log(self._status_message)if self.canPreview:@@ -845,18 +909,147 @@ class AppBridge(QObject):worker.signals.finished.connect(finished)worker.signals.failed.connect(- lambda error: self._finish_lut_auto(worker, f"Auto color failed: {error}"))+ lambda error: self._finish_lut_auto(worker, UiMessage("Auto color failed: %1", error)))+ worker.signals.cancelled.connect(+ lambda: self._finish_lut_auto(worker, UiMessage("Auto color cancelled.")))+ self._thread_pool.start(worker)++ @Property(str, notify=settingsUpdated)+ def lutReferenceImage(self) -> str:+ return self._settings.lut_reference_image++ @Property(bool, notify=lutReferenceChanged)+ def lutReferenceBusy(self) -> bool:+ return self._lut_reference_worker is not None++ @Property(str, notify=lutReferenceChanged)+ def lutReferenceStatus(self) -> str:+ return translate_text(self._lut_reference_status)++ def _reference_status(self, message: str) -> None:+ self._lut_reference_status = message+ self.lutReferenceChanged.emit()++ def _finish_lut_reference(self, worker: JobWorker, message: str) -> None:+ if self._lut_reference_worker is not worker:+ return+ self._lut_reference_worker = None+ if not self._shutting_down:+ self._reference_status(message)+ if message:+ self._status_message = message+ self.statusMessageChanged.emit()+ self._log(message)++ @Slot(str)+ def setLutReferenceImage(self, file_url_or_path: str) -> None:+ if self._shutting_down or self._lut_auto_worker is not None:+ return+ path = self._clean_path(file_url_or_path)+ if path and (Path(path).suffix.lower() not in IMAGE_SUFFIXES or not Path(path).is_file()):+ self._reference_status(UiMessage("Choose an existing reference image."))+ return+ if not self._save_setting(lut_reference_image=path):+ return+ if self._lut_reference_worker is not None:+ self._lut_reference_worker.controller.stop()+ self._lut_reference_worker = None+ if not path:+ self._reference_status("")+ return+ if self._active_tab != "neural-rendering" or self._operation_state != IDLE:+ self._reference_status(UiMessage("Select an input and wait for the current operation before matching."))+ return+ context_key = self._context_key()+ mode = "Image" if context_key == "nr-image" else "Video"+ if mode == "Image" and self._settings.coloring_mode != "LUT":+ self._reference_status(UiMessage("Select Apply LUT to match the reference with Color Adjustment."))+ return+ source = self._queue_for_context(context_key).selected_path()+ if not source or not Path(source).is_file():+ self._reference_status(UiMessage("Select an input image or video before choosing a reference."))+ return++ snapshot = self._settings+ context = self._contexts[context_key]+ generation = context.generation+ source_path = os.path.normcase(os.path.abspath(source))+ reference_identity = self._color_file_identity(path)+ source_identity = self._color_file_identity(source)+ lut_identity = self._color_file_identity(snapshot.lut_path)+ worker = JobWorker(+ analyze_color_reference, source, path, snapshot, mode,+ duration_seconds=context.duration_seconds,+ video_size=(context.source_width, context.source_height) if mode == "Video" else None,+ hdr=context.source_hdr,+ )+ worker.controller.ffmpeg_device = snapshot.ffmpeg_device+ self._lut_reference_worker = worker+ self._reference_status(UiMessage("Analyzing input and reference colors…"))++ def progress(value: float, message: str) -> None:+ if self._lut_reference_worker is worker and not self._shutting_down:+ self._reference_status(UiMessage("%1… %2%", message, round(value * 100)))++ def finished(values: dict[str, int | float]) -> None:+ if self._lut_reference_worker is not worker or self._shutting_down:+ return+ current_source = self._queue_for_context(context_key).selected_path() or ""+ current_source = os.path.normcase(os.path.abspath(current_source)) if current_source else ""+ controls_unchanged = (+ self._settings.lut_path == snapshot.lut_path+ and self._settings.lut_resolution == snapshot.lut_resolution+ and self._settings.coloring_mode == snapshot.coloring_mode+ and self._settings.lut_reference_image == path+ and all(getattr(self._settings, key) == getattr(snapshot, key)+ for key in LUT_ADJUSTMENT_RANGES)+ )+ if (self._context_key() != context_key or self._active_tab != "neural-rendering"+ or self._contexts[context_key].generation != generation+ or current_source != source_path or not controls_unchanged+ or self._color_file_identity(path) != reference_identity+ or self._color_file_identity(source) != source_identity+ or self._color_file_identity(snapshot.lut_path) != lut_identity):+ self._finish_lut_reference(worker, UiMessage("Reference match skipped because the input or color controls changed."))+ return+ # Matching must never overwrite either control above the action row.+ values = {key: value for key, value in values.items()+ if key in LUT_ADJUSTMENT_RANGES and key != "lut_mix"}+ if not self._save_setting(**values):+ self._finish_lut_reference(worker, UiMessage("Reference match could not be applied during the current operation."))+ return+ self._finish_lut_reference(worker, "")+ if self.canPreview:+ if self._auto_preview_enabled:+ self._schedule_auto_preview(90)+ else:+ self.renderPreview()++ worker.signals.progress.connect(progress)+ worker.signals.finished.connect(finished)+ worker.signals.failed.connect(+ lambda error: self._finish_lut_reference(worker, UiMessage("Reference matching failed: %1", error)))worker.signals.cancelled.connect(- lambda: self._finish_lut_auto(worker, "Auto color cancelled."))+ lambda: self._finish_lut_reference(worker, UiMessage("Reference matching cancelled.")))self._thread_pool.start(worker)+ @staticmethod+ def _color_file_identity(path: str) -> tuple | None:+ if not path:+ return None+ try:+ stat = Path(path).stat()+ return stat.st_size, stat.st_mtime_ns, stat.st_ctime_ns+ except OSError:+ return None+@Property(bool, notify=lutSaveChanged)def lutSaveBusy(self) -> bool:return self._lut_save_worker is not None@Property(str, notify=lutSaveChanged)def lutSaveStatus(self) -> str:- return self._lut_save_status+ return translate_text(self._lut_save_status)def _finish_lut_save(self, message: str) -> None:self._lut_save_worker = None@@ -876,11 +1069,11 @@ class AppBridge(QObject):snapshot = self._settingsworker = JobWorker(save_cube_lut, target, snapshot.lut_path or None, snapshot)self._lut_save_worker = worker- self._lut_save_status = f"Saving {snapshot.lut_resolution}³ LUT…"+ self._lut_save_status = UiMessage("Saving %1³ LUT…", snapshot.lut_resolution)self.lutSaveChanged.emit()- worker.signals.finished.connect(lambda path: self._finish_lut_save(f"Saved LUT to {path}"))- worker.signals.failed.connect(lambda error: self._finish_lut_save(f"LUT export failed: {error}"))- worker.signals.cancelled.connect(lambda: self._finish_lut_save("LUT export cancelled."))+ worker.signals.finished.connect(lambda path: self._finish_lut_save(UiMessage("Saved LUT to %1", path)))+ worker.signals.failed.connect(lambda error: self._finish_lut_save(UiMessage("LUT export failed: %1", error)))+ worker.signals.cancelled.connect(lambda: self._finish_lut_save(UiMessage("LUT export cancelled.")))self._thread_pool.start(worker)@Slot(str, bool)@@ -921,7 +1114,8 @@ class AppBridge(QObject):self._upscale_mode = modeself.upscaleModeChanged.emit()self._emit_context()- self._schedule_auto_preview(180)+ if not getattr(self, "_import_switching_mode", False) and not self._load_active_selection_if_needed():+ self._schedule_auto_preview(180)@Property(str, notify=settingsUpdated)def upscalePreviewLength(self) -> str:@@ -951,7 +1145,11 @@ class AppBridge(QObject):@Property(str, notify=statusMessageChanged)def statusMessage(self) -> str:- return self._status_message+ return translate_text(self._status_message)++ @Property(str, notify=mediaPreviewChanged)+ def previewError(self) -> str:+ return self._context().preview_error@Property(float, notify=splitPositionChanged)def splitPosition(self) -> float:@@ -1022,11 +1220,11 @@ class AppBridge(QObject):@Property(str, notify=presetStatusChanged)def presetStatus(self) -> str:- return self._preset_status+ return translate_text(self._preset_status)@Property(str, notify=liveStatusTextChanged)def liveStatusText(self) -> str:- return self._live_status_text+ return translate_text(self._live_status_text)@Property(bool, notify=isLiveRunningChanged)def isLiveRunning(self) -> bool:@@ -1102,6 +1300,34 @@ class AppBridge(QObject):def _on_mpv_embed_error(self, message: str) -> None:self._log(f"Live player: {message}")+ @property+ def _auto_preview_pending(self) -> bool:+ return getattr(self, "_queued_auto_preview", False)++ @_auto_preview_pending.setter+ def _auto_preview_pending(self, value: bool) -> None:+ changed = self._auto_preview_pending != bool(value)+ self._queued_auto_preview = bool(value)+ if changed:+ self.previewBusyChanged.emit()++ @property+ def _scrub_pending_pos(self) -> float | None:+ return getattr(self, "_queued_scrub_position", None)++ @_scrub_pending_pos.setter+ def _scrub_pending_pos(self, value: float | None) -> None:+ changed = (self._scrub_pending_pos is None) != (value is None)+ self._queued_scrub_position = value+ if changed:+ self.previewBusyChanged.emit()++ @Property(bool, notify=previewBusyChanged)+ def previewBusy(self) -> bool:+ """Include debounced work so the previous frame cannot be peeked."""+ return (self._operation_state in {PREVIEW_PREPARING, PREVIEW_RUNNING, PREVIEW_CANCELLING}+ or self._auto_preview_pending or self._scrub_pending_pos is not None or self.lutAutoBusy)+@Property(str, notify=operationStateChanged)def operationState(self) -> str:return self._operation_state@@ -1116,11 +1342,13 @@ class AppBridge(QObject):@Property(bool, notify=operationStateChanged)def canPreview(self) -> bool:- return self._operation_state == IDLE and self._runtime_state == "Ready" and not self._is_live_running+ return (self._operation_state == IDLE and self._runtime_state == "Ready"+ and not self._is_live_running and not self.lutAutoBusy and self._preview_processing_enabled())@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()+ return (self._operation_state == IDLE and self._runtime_state == "Ready"+ and not self._is_live_running and not self.lutAutoBusy and self._active_render_configuration_valid())@Property(bool, notify=operationStateChanged)def canStartLive(self) -> bool:@@ -1184,7 +1412,7 @@ class AppBridge(QObject):@queueHeight.setterdef queueHeight(self, value: int) -> None:- value = max(120, min(360, int(value)))+ value = max(180, min(720, int(value)))if value != self._queue_height:self._queue_height = valueself._ui_settings.setValue("layout/queueHeight", value)@@ -1237,7 +1465,7 @@ class AppBridge(QObject):if cleaned == self._export_folder:returnself._export_folder = cleaned- self._ui_settings.setValue("export/folder", cleaned)+ self._ui_settings.setValue("export/folder", encode_app_path(cleaned))self._ui_settings.sync()self.exportPrefsChanged.emit()@@ -1245,6 +1473,30 @@ class AppBridge(QObject):def autoPreviewEnabled(self) -> bool:return self._auto_preview_enabled+ @Property(list, constant=True)+ def languageChoices(self) -> list[dict[str, str]]:+ return language_choices()++ @Property(str, notify=languageChanged)+ def language(self) -> str:+ return self._language_manager.language++ @language.setter+ def language(self, value: str) -> None:+ if value not in LANGUAGE_CODES or value == self.language:+ return+ self._language_manager.set_language(value)+ self._ui_settings.setValue("interface/language", value)+ self._ui_settings.sync()+ self.languageChanged.emit()+ # Re-evaluate Python presentation properties as well as QML bindings.+ for signal in (self.statusMessageChanged, self.presetStatusChanged,+ self.liveStatusTextChanged, self.settingsUpdated,+ self.runtimeStateChanged, self.gpuChoicesChanged,+ self.estimateChanged, self.lutSaveChanged,+ self.lutAutoChanged, self.lutReferenceChanged):+ signal.emit()+@autoPreviewEnabled.setterdef autoPreviewEnabled(self, value: bool) -> None:value = bool(value)@@ -1258,29 +1510,63 @@ class AppBridge(QObject):else:self._auto_preview_pending = Falseself._auto_preview_timer.stop()+ self._scrub_pending_pos = None+ self._scrub_preview_timer.stop()- def _auto_preview_fingerprint(self, context_key: str | None = None) -> tuple:- """Snapshot what the current output preview was rendered from.+ def _preview_processing_enabled(self, context_key: str | None = None) -> bool:+ key = context_key or self._context_key()+ return (key not in {"nr-image", "nr-video"}+ or bool(enabled_stages(self._settings, "Image" if key == "nr-image" else "Video")))- Returns ``(selected source, relevant 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). Shared fields edited on another- tab (AI/video GPU, preview encoding) still mark this context stale.- Upscale's manual clip duration is excluded because it does not alter- already rendered footage. Returns ``()`` on error.- """+ def _skip_unprocessed_preview(self, context_key: str | None = None) -> bool:+ """Use the original player when every processing card is off."""+ key = context_key or self._context_key()+ if self._preview_processing_enabled(key):+ return False+ if key == self._context_key():+ self._auto_preview_pending = False+ self._auto_preview_timer.stop()+ self._scrub_pending_pos = None+ self._scrub_preview_timer.stop()+ if self._operation_state in {PREVIEW_PREPARING, PREVIEW_RUNNING}:+ self._invalidate_preview_generation()+ if self._active_worker is not None:+ self._active_worker.controller.stop()+ self._operation_state = PREVIEW_CANCELLING+ self.operationStateChanged.emit()+ self._clear_output_preview(key)+ self._clear_rendered_ranges(key)+ return True++ def _auto_preview_fingerprint(self, context_key: str | None = None, *,+ start_seconds: float | None = None) -> tuple:+ """Identify source, active settings and the requested timeline frame."""try:key = context_key or self._context_key()queue = self._queue_for_context(key)source = queue.selected_path() or ""+ if key in {"nr-image", "nr-video"}:+ ctx = self._contexts[key]+ mode = "Image" if key == "nr-image" else "Video"+ snapshot = preview_settings_key(self._settings, mode, hdr=ctx.source_hdr)+ source_key = cache_key({"source": optional_file_identity(source)}) if source else ""+ seconds = ctx.last_playhead_seconds if start_seconds is None else start_seconds+ frame = 0+ if mode == "Video":+ fps = ctx.source_fps+ frame = max(1, int(math.floor(max(0.0, seconds) * fps + 1e-6)) + 1) if fps > 0 else seconds+ if fps > 0 and ctx.duration_seconds > 0:+ frame = min(frame, max(1, int(round(ctx.duration_seconds * fps))))+ return (os.path.normcase(os.path.abspath(source)) if source else "", source_key, snapshot, frame)try:snapshot = tuple(getattr(self._settings, field.name, None)for field in _dataclass_fields(self._settings)if not (- (key == "upscale-video" and field.name == "upscale_preview_length")+ field.name in {"cache_memory_mode", "cache_codec"}+ or (key == "upscale-video" and field.name == "upscale_preview_length")or (key == "nr-video" and field.name == "nr_preview_length")+ or (key.endswith("video") and field.name in self.VIDEO_EXPORT_FIELDS)))except Exception:@@ -1303,6 +1589,22 @@ class AppBridge(QObject):return Falsereturn enabled_stages(self._settings, mode) == ("coloring",)+ def _has_current_preview(self, context_key: str, *, start_seconds: float | None = None) -> bool:+ ctx = self._contexts[context_key]+ previous = ctx.last_auto_fingerprint+ if not ctx.has_output or not previous:+ return False+ current = self._auto_preview_fingerprint(context_key, start_seconds=start_seconds)+ if previous == current:+ return True+ # A rendered clip already contains every frame in its green range.+ # Returning to the tab inside that range must keep the playable clip.+ if (context_key == "nr-video" and ctx.output_is_video+ and len(previous) == 4 and len(current) == 4 and previous[:3] == current[:3]):+ seconds = ctx.last_playhead_seconds if start_seconds is None else start_seconds+ return any(item["start"] <= seconds < item["end"] for item in ctx.rendered_ranges)+ return False+def _schedule_auto_preview(self, delay_ms: int = 360, *, throttle: bool = False) -> None:"""Debounce an automatic preview for the currently selected media.@@ -1315,6 +1617,10 @@ class AppBridge(QObject):disabled for fi-video even when the global switch is on, so settingstweaks and tab switches never trigger automatic renders there."""+ if self.lutAutoBusy:+ return+ if self._active_tab == "neural-rendering" and self._skip_unprocessed_preview():+ returnif self._context_key() == "fi-video" or (self._context_key() == "nr-video" and"frame_generation" in enabled_stages(self._settings, "Video")@@ -1345,15 +1651,13 @@ class AppBridge(QObject):# 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+ if self._has_current_preview(key):+ self._auto_preview_pending = False+ try:+ self._auto_preview_timer.stop()+ except Exception:+ pass+ returnexcept Exception:pass@@ -1368,7 +1672,7 @@ class AppBridge(QObject):except Exception:passself._operation_state = PREVIEW_CANCELLING- self._status_message = "Updating realtime preview…"+ self._status_message = UiMessage("Updating realtime preview…")self.operationStateChanged.emit()self.statusMessageChanged.emit()if throttle and self._auto_preview_timer.isActive():@@ -1378,6 +1682,11 @@ class AppBridge(QObject):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.lutAutoBusy:+ self._auto_preview_pending = False+ return+ if self._skip_unprocessed_preview():+ returnif self._operation_state == IDLE:self._auto_preview_pending = Falseself.renderPreview()@@ -1409,6 +1718,12 @@ class AppBridge(QObject):@Property(str, notify=runtimeStateChanged)def gpuName(self) -> str:if self._prepared is None:+ if self._runtime_state == "Ready":+ from ..core.ffmpeg.vulkan import filter_device+ try:+ return filter_device(self._settings.ffmpeg_device).name+ except (RuntimeError, ValueError):+ passreturn "Initializing GPU…" if self._runtime_state == "Initializing" else "GPU unavailable"return self._display_gpu().get("display_name", "NVIDIA GPU")@@ -1548,9 +1863,17 @@ class AppBridge(QObject):def imageFormatChoices(self) -> list[str]:return ["PNG", "JPEG", "WebP", "AVIF", "TIFF"]- @Property(list, constant=True)+ @Property(list, notify=settingsUpdated)def containerChoices(self) -> list[str]:- return list(CONTAINER_CHOICES)+ return list(containers_for_codec(self._settings.codec))++ @Property(list, notify=settingsUpdated)+ def upscaleContainerChoices(self) -> list[str]:+ return list(containers_for_codec(self._settings.upscale_codec))++ @Property(list, notify=settingsUpdated)+ def fiContainerChoices(self) -> list[str]:+ return list(containers_for_codec(self._settings.frame_interpolation_codec))@Property(list, constant=True)def codecChoices(self) -> list[str]:@@ -1588,10 +1911,6 @@ class AppBridge(QObject):def nrPreviewLengthChoices(self) -> list[dict[str, str]]:return [{"label": f"{value}s", "value": value} for value 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)@@ -1667,16 +1986,21 @@ class AppBridge(QObject):self._prepared = prepare_runtime()self._normalize_gpu_selections()except Exception as exc:- message = str(exc)- 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)- app_log.error("startup", self._status_message)- return+ try:+ from ..core.ffmpeg.vulkan import filter_device+ filter_device(self._settings.ffmpeg_device)+ self._startup_warnings.append(f"NVIDIA AI processing is unavailable: {exc}")+ except Exception:+ message = str(exc)+ self._runtime_state = "Failed"+ self._runtime_error = message+ self.runtimeStateChanged.emit()+ self.operationStateChanged.emit()+ self._status_message = UiMessage("Runtime initialization failed: %1", message)+ self.statusMessageChanged.emit()+ self._log(self._status_message)+ app_log.error("startup", self._status_message)+ return# Load optional native bridges without selecting an adapter. Their# absence must not prevent the other rendering modes from opening.@@ -1691,7 +2015,7 @@ class AppBridge(QObject):self._runtime_state = "Ready"self._runtime_error = ""- self._status_message = "Ready."+ self._status_message = UiMessage("Ready.")self.runtimeStateChanged.emit()self.gpuChoicesChanged.emit()self.operationStateChanged.emit()@@ -1737,60 +2061,58 @@ class AppBridge(QObject):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._status_message = UiMessage("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+ for codec_key, container_key, hdr_key in (+ ("codec", "container", "hdr_mode"),+ ("frame_interpolation_codec", "frame_interpolation_container", "frame_interpolation_hdr_mode"),+ ("upscale_codec", "upscale_container", "upscale_hdr_enabled"),+ ):+ codec = str(changed.get(codec_key, getattr(self._settings, codec_key)))+ if codec_key in changed:+ container = changed.get(container_key, getattr(self._settings, container_key))+ if container not in containers_for_codec(codec):+ changed[container_key] = container_for_codec(codec)+ if codec_key in changed and not hdr_mode_supported(codec):+ changed[hdr_key] = Falsecandidate = replace(self._settings, **changed)if candidate.upscale_engine != "DLSS" and 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._status_message = UiMessage("Upscale Video requires VSR or RTX Video HDR to remain enabled.")self.statusMessageChanged.emit()self.settingsUpdated.emit()return Falsetry:candidate = _validate(candidate)except Exception as exc:- self._status_message = f"Invalid setting: {exc}"+ self._status_message = UiMessage("Invalid setting: %1", exc)self.statusMessageChanged.emit()self.settingsUpdated.emit()self._log(self._status_message)return False+ nr_before = {key: self._auto_preview_fingerprint(key) for key in ("nr-image", "nr-video")}self._settings = candidateSETTINGS_STATE.current = self._settings+ nr_changed = set()+ for key, previous in nr_before.items():+ current = self._auto_preview_fingerprint(key)+ if not previous or not current or previous != current:+ nr_changed.add(key)keep_nr_video_output = (self._context_key() == "nr-video"and self._auto_preview_enabledand self._runtime_state == "Ready"and self._contexts["nr-video"].has_output+ and self._preview_processing_enabled("nr-video")and "frame_generation" not in enabled_stages(self._settings, "Video"))- if keep_nr_video_output and set(changed) & (- self.PROCESSING_PREVIEW_FIELDS["nr-video"] | {"video_stage_order", "video_enabled_stages"}- ):- self._contexts["nr-video"].last_auto_fingerprint = ()- if any(key in changed for key in ("image_stage_order", "image_enabled_stages")):- self._clear_output_preview("nr-image")- if (not keep_nr_video_output- and any(key in changed for key in ("video_stage_order", "video_enabled_stages"))):- self._clear_output_preview("nr-video")if (self._context_key() == "nr-video"and "frame_generation" in enabled_stages(self._settings, "Video")- and any(key in self.AUTO_PREVIEW_FIELDS for key in changed)):+ and "nr-video" in nr_changed):self._clear_output_preview("nr-video")if self._operation_state in {PREVIEW_PREPARING, PREVIEW_RUNNING}:self._invalidate_preview_generation()@@ -1800,19 +2122,23 @@ class AppBridge(QObject):keep_coloring_output = (self._auto_preview_enabledand set(changed).issubset(coloring_changes)and self._can_fast_color_preview(self._context_key()))+ for key in nr_changed:+ if ((keep_coloring_output and key == self._context_key())+ or (keep_nr_video_output and key == "nr-video")):+ # Keep the last frame painted until its replacement is ready.+ self._contexts[key].last_auto_fingerprint = ()+ else:+ self._clear_output_preview(key)+ self._skip_unprocessed_preview(key)for context_key, fields in self.PROCESSING_PREVIEW_FIELDS.items():+ if context_key in {"nr-image", "nr-video"}:+ continueif any(field in changed for field in fields):- if ((keep_coloring_output and context_key == self._context_key())- or (keep_nr_video_output and context_key == "nr-video")):- # Keep the last frame painted until its replacement is- # ready; the fingerprint still marks it as stale.- self._contexts[context_key].last_auto_fingerprint = ()- else:- self._clear_output_preview(context_key)+ self._clear_output_preview(context_key)if self._is_live_running and any(field in self.LIVE_EFFECT_FIELDS for field in changed):self._live_effects_dirty = Trueif 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._status_message = UiMessage("Setting saved; this change applies the next time Live is started.")self.statusMessageChanged.emit()self.settingsUpdated.emit()self.estimateChanged.emit()@@ -1828,9 +2154,11 @@ class AppBridge(QObject):self._clear_rendered_ranges("fi-video")if any(field in self.UPSCALE_RANGE_FIELDS for field in changed):self._clear_rendered_ranges("upscale-video")- if any(field in self.NR_RANGE_FIELDS | self.UPSCALE_RANGE_FIELDS | self.FI_RANGE_FIELDS for field in changed):+ if "nr-video" in nr_changed:self._clear_rendered_ranges("nr-video")- if any(field in self.AUTO_PREVIEW_FIELDS for field in changed):+ if (any(field in self.AUTO_PREVIEW_FIELDS for field in changed)+ and (self._context_key() not in {"nr-image", "nr-video"}+ or self._context_key() in nr_changed)):delay = 90 if keep_coloring_output else 360self._schedule_auto_preview(delay, throttle=keep_coloring_output)return True@@ -2136,7 +2464,7 @@ class AppBridge(QObject):@Property(str, notify=settingsUpdated)def customMaskStatus(self) -> str:- return mask_status(self._settings.nr_mask)+ return translate_text(mask_status(self._settings.nr_mask))# Output & Format settings@Property(str, notify=settingsUpdated)@@ -2188,13 +2516,15 @@ class AppBridge(QObject):@videoCodec.setterdef 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)+ self._save_setting(codec=val)@Property(str, notify=settingsUpdated)def videoContainer(self) -> str:- return container_for_codec(self._settings.codec)+ return resolve_container(self._settings.codec, self._settings.container)++ @videoContainer.setter+ def videoContainer(self, val: str) -> None:+ self._save_setting(container=val)@Property(str, notify=settingsUpdated)def videoQuality(self) -> str:@@ -2472,13 +2802,15 @@ class AppBridge(QObject):@upscaleCodec.setterdef 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)+ self._save_setting(upscale_codec=val)@Property(str, notify=settingsUpdated)def upscaleContainer(self) -> str:- return container_for_codec(self._settings.upscale_codec)+ return resolve_container(self._settings.upscale_codec, self._settings.upscale_container)++ @upscaleContainer.setter+ def upscaleContainer(self, val: str) -> None:+ self._save_setting(upscale_container=val)@Property(str, notify=settingsUpdated)def upscaleQuality(self) -> str:@@ -2546,13 +2878,15 @@ class AppBridge(QObject):@fiCodec.setterdef 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)+ self._save_setting(frame_interpolation_codec=val)@Property(str, notify=settingsUpdated)def fiContainer(self) -> str:- return container_for_codec(self._settings.frame_interpolation_codec)+ return resolve_container(self._settings.frame_interpolation_codec, self._settings.frame_interpolation_container)++ @fiContainer.setter+ def fiContainer(self, val: str) -> None:+ self._save_setting(frame_interpolation_container=val)@Property(str, notify=settingsUpdated)def fiQuality(self) -> str:@@ -2609,6 +2943,22 @@ class AppBridge(QObject):return hdr_mode_supported(self._settings.upscale_codec)# Global Preferences+ @Property(str, notify=settingsUpdated)+ def cacheMemoryMode(self) -> str:+ return self._settings.cache_memory_mode++ @cacheMemoryMode.setter+ def cacheMemoryMode(self, val: str) -> None:+ self._save_setting(cache_memory_mode=val)++ @Property(str, notify=settingsUpdated)+ def cacheCodec(self) -> str:+ return self._settings.cache_codec++ @cacheCodec.setter+ def cacheCodec(self, val: str) -> None:+ self._save_setting(cache_codec=val)+@Property(str, notify=settingsUpdated)def aiGpuUuid(self) -> str:return self._settings.ai_gpu_uuid@@ -2625,14 +2975,6 @@ class AppBridge(QObject):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)-def _active_render_configuration_valid(self) -> bool:try:_validate(self._settings)@@ -2664,33 +3006,33 @@ class AppBridge(QObject):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 ""+ return translate_text("")except Exception as exc:- return str(exc)+ return translate_text(str(exc))@Property(str, notify=estimateChanged)def outputEstimate(self) -> str:context = self._context()width, height = context.source_width, context.source_heightif width <= 0 or height <= 0:- return ""+ return translate_text("")try:if self._active_tab == "neural-rendering":result = estimate_pipeline(width, height, context.source_fps, context.source_hdr,self._settings, self._nr_mode)fps = f" | {result.fps:g} FPS" if self._nr_mode == "Video" and result.fps else ""- return f"{width}×{height} → {result.width}×{result.height}{fps}"+ return translate_text(f"{width}×{height} → {result.width}×{result.height}{fps}")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}"+ return translate_text(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}"+ return translate_text(f"{width}×{height} → {ow}×{oh}{note}")if self._active_tab == "frame-interpolation":- return f"Target {self._settings.frame_interpolation_target_fps} FPS"+ return translate_text(UiMessage("Target %1 FPS", self._settings.frame_interpolation_target_fps))except Exception as exc:- return f"Output unavailable: {exc}"- return ""+ return translate_text(UiMessage("Output unavailable: %1", exc))+ return translate_text("")# =========================================================================# Methods & Slots: Presets & Defaults@@ -2718,11 +3060,13 @@ class AppBridge(QObject):@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._preset_status = UiMessage("Stop the current operation before resetting settings.")self.presetStatusChanged.emit()returnself._settings = DEFAULT_SETTINGSSETTINGS_STATE.current = self._settings+ self._skip_unprocessed_preview("nr-image")+ self._skip_unprocessed_preview("nr-video")self._clear_rendered_ranges("fi-video")self._clear_rendered_ranges("upscale-video")self._clear_rendered_ranges("nr-video")@@ -2736,7 +3080,8 @@ class AppBridge(QObject):self.settingsUpdated.emit()self.workflowStagesChanged.emit()self.runtimeStateChanged.emit()- self._preset_status = "All settings were reset to factory defaults."+ self.operationStateChanged.emit()+ self._preset_status = UiMessage("All settings were reset to factory defaults.")self.presetStatusChanged.emit()self._log("Reset all settings to factory defaults.")@@ -2750,8 +3095,9 @@ class AppBridge(QObject):TAB_RESET_NEURAL_FIELDS = ("image_stage_order", "video_stage_order","image_enabled_stages", "video_enabled_stages",- "denoise_strength", "denoise_deblock", "denoise_temporal", "cas_sharpness", "sharpening_method",+ "cas_sharpness", "sharpening_method","coloring_mode", "color_match_source", "color_match_reference", "lut_path",+ "lut_reference_image","lut_resolution", *LUT_ADJUSTMENT_RANGES,"nr_style", "nr_intensity", "nr_passes","local_tone_strength", "local_structure_strength",@@ -2795,7 +3141,7 @@ class AppBridge(QObject):else:returnif self._operation_state not in {IDLE, LIVE_RUNNING}:- self._preset_status = "Stop the current operation before resetting settings."+ self._preset_status = UiMessage("Stop the current operation before resetting settings.")self.presetStatusChanged.emit()returnvalues = {name: getattr(DEFAULT_SETTINGS, name) for name in names}@@ -2806,7 +3152,7 @@ class AppBridge(QObject):self.upscaleModeChanged.emit()self._emit_context()label = self.TAB_RESET_LABELS[tab]- self._preset_status = f"{label} settings were reset to defaults."+ self._preset_status = UiMessage("%1 settings were reset to defaults.", UiMessage(label))self.presetStatusChanged.emit()self._flush_settings()self._log(f"Reset {label} settings to defaults.")@@ -2814,24 +3160,24 @@ class AppBridge(QObject):@Slot(str, result=str)def exportPreset(self, name: str) -> str:if not name.strip():- self._preset_status = "Please enter a preset name."+ self._preset_status = UiMessage("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._preset_status = UiMessage("Exported preset '%1' to %2", name, 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._preset_status = UiMessage("Export failed: %1", 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._preset_status = UiMessage("Please enter a preset name.")self.presetStatusChanged.emit()return ""path = self._clean_path(file_url_or_path)@@ -2839,19 +3185,19 @@ class AppBridge(QObject):return ""try:written = export_settings_preset_to(name, self._settings, path)- self._preset_status = f"Exported preset '{name}' to {written.name}"+ self._preset_status = UiMessage("Exported preset '%1' to %2", name, 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._preset_status = UiMessage("Export failed: %1", 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._preset_status = UiMessage("Stop the current operation before importing a preset.")self.presetStatusChanged.emit()return Falsepath = self._clean_path(file_url_or_path)@@ -2863,6 +3209,8 @@ class AppBridge(QObject):self._clear_output_preview("nr-image")self._clear_output_preview("nr-video")self._clear_rendered_ranges("nr-video")+ self._skip_unprocessed_preview("nr-image")+ self._skip_unprocessed_preview("nr-video")if self._upscale_mode != imported.upscale_mode:self._upscale_mode = imported.upscale_modeself.upscaleModeChanged.emit()@@ -2873,12 +3221,13 @@ class AppBridge(QObject):self.settingsUpdated.emit()self.workflowStagesChanged.emit()self.runtimeStateChanged.emit()- self._preset_status = f"Imported preset '{name}' successfully."+ self.operationStateChanged.emit()+ self._preset_status = UiMessage("Imported preset '%1' successfully.", name)self.presetStatusChanged.emit()self._log(f"Imported preset '{name}' from {path}")return Trueexcept Exception as exc:- self._preset_status = f"Import failed: {exc}"+ self._preset_status = UiMessage("Import failed: %1", exc)self.presetStatusChanged.emit()return False@@ -2894,6 +3243,18 @@ class AppBridge(QObject):return self._fi_queuereturn self._nr_image_queue+ def _load_active_selection_if_needed(self) -> bool:+ """Show a queued source when its mode is opened for the first time."""+ if self._operation_state != IDLE or self._active_tab not in {"neural-rendering", "upscale", "frame-interpolation"}:+ return False+ key = self._context_key()+ queue = self._queue_for_context(key)+ selected = queue.selected_path()+ if selected and (not self._contexts[key].input_url or self._contexts[key].selected_path != selected):+ self.selectQueueItem(queue.selectedIndex)+ return True+ return False+def _queue_for_context(self, key: str) -> BatchListModel:return {"nr-image": self._nr_image_queue,@@ -2916,101 +3277,48 @@ class AppBridge(QObject):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] = []+ def _expand_inputs_by_kind(self, file_urls: list[str], controller=None,+ progress=None) -> dict[str, list[str]]:+ """Scan once, preserving drop order and separating images from videos."""+ collected: dict[str, list[str]] = {"image": [], "video": []}+ seen: dict[str, set[str]] = {"image": set(), "video": set()}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 []+ return {"image": [], "video": []}clean = self._clean_path(value)if not clean:continuepath = 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()))+ try:+ candidates = (sorted((item for item in path.rglob("*")+ if self._classify_media_suffix(item.suffix) is not None),+ key=lambda item: str(item).casefold())+ if path.is_dir() else [path])+ for item in candidates:+ if controller is not None and controller.cancel.is_set():+ return {"image": [], "video": []}+ kind = self._classify_media_suffix(item.suffix)+ if kind is None or not item.is_file():+ continue+ resolved = str(item.resolve())+ identity = os.path.normcase(os.path.abspath(resolved))+ if identity not in seen[kind]:+ seen[kind].add(identity)+ collected[kind].append(resolved)+ except (OSError, PermissionError):+ continueif 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+ return collected@Slot(list)def addFiles(self, file_urls: list[str]) -> None:if not file_urls:returnif not self.canModifyQueue:- self._status_message = "Queue changes are disabled while an operation is active."+ self._status_message = UiMessage("Queue changes are disabled while an operation is active.")self.statusMessageChanged.emit()self._paste_select_single = Falsereturn@@ -3019,37 +3327,15 @@ class AppBridge(QObject):# so its preview loads immediately.select_pasted_single = self._paste_select_singleself._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)+ # Scan in the worker once, then route each kind to its own queue.+ # A mixed drop keeps the current mode and preview selected.+ source_tab = self._active_tab+ queue_keys = (("nr-image", "nr-video") if source_tab == "neural-rendering" else+ ("upscale-image", "upscale-video") if source_tab == "upscale" else+ ("fi-video",))+ operation_id = self._set_operation(SCANNING_INPUTS, UiMessage("Scanning selected inputs…"))++ worker = JobWorker(self._expand_inputs_by_kind, list(file_urls))self._scan_worker = workerdef on_progress(fraction: float, message: str) -> None:@@ -3060,19 +3346,60 @@ class AppBridge(QObject):self.overallProgressChanged.emit()self.statusMessageChanged.emit()- def done(valid_paths: list[str]) -> None:+ def done(valid_by_kind: dict[str, list[str]]) -> None:if operation_id != self._operation_id or self._shutting_down:returnself._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}"+ added_by_kind = {"image": 0, "video": 0}+ for key in queue_keys:+ kind = "image" if key.endswith("image") else "video"+ queue = self._queue_for_context(key)+ before = queue.count+ queue.add_items(valid_by_kind[kind])+ added = queue.count - before+ added_by_kind[kind] += added+ if added:+ self._load_queue_metadata_async(key)+ total_added = sum(added_by_kind.values())+ if total_added:+ parts = [f"{count} {kind}{'s' if count != 1 else ''}"+ for kind, count in added_by_kind.items() if count]+ message = f"Added {' and '.join(parts)}."+ else:+ message = "No new supported files were found."self._finish_operation(operation_id, message)- if self._context_key() == context_key:+ auto_switched: str | None = None+ if source_tab == self._active_tab and source_tab in {"neural-rendering", "upscale"}:+ images = bool(valid_by_kind["image"])+ videos = bool(valid_by_kind["video"])+ if images != videos:+ target = "Image" if images else "Video"+ previous = self._upscale_mode if source_tab == "upscale" else self._nr_mode+ if previous != target:+ # Selection below handles the new source, including+ # Ctrl+V's select-new-item behavior. Suppress a second+ # metadata load in the mode setter during this switch.+ self._import_switching_mode = True+ try:+ if source_tab == "upscale":+ self.upscaleMode = target+ else:+ self.nrMode = target+ finally:+ self._import_switching_mode = False+ current = self._upscale_mode if source_tab == "upscale" else self._nr_mode+ if current == target:+ auto_switched = target+ if auto_switched and total_added:+ message = UiMessage("Switched to %1 mode. %2", auto_switched, message)+ self._status_message = message+ self.statusMessageChanged.emit()+ active_key = self._context_key()+ if source_tab == self._active_tab and active_key in queue_keys:+ queue = self._queue_for_context(active_key)+ kind = "image" if active_key.endswith("image") else "video"+ added = added_by_kind[kind]+ valid_paths = valid_by_kind[kind]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.@@ -3091,20 +3418,94 @@ class AppBridge(QObject):breakexcept Exception:continue- elif added:- row = queue.selectedIndex if queue.selectedIndex >= 0 else 0- self.selectQueueItem(row)+ else:+ self._load_active_selection_if_needed()self._log(message)def failed(message: str) -> None:self._scan_worker = None- self._finish_operation(operation_id, f"Input scan failed: {message}")+ self._finish_operation(operation_id, UiMessage("Input scan failed: %1", 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."))+ worker.signals.cancelled.connect(lambda: self._finish_operation(operation_id, UiMessage("Input scan cancelled.")))+ self._thread_pool.start(worker)++ def _load_queue_metadata_async(self, context_key: str) -> None:+ """Populate all list rows without changing the selected preview or operation."""+ queue = self._queue_for_context(context_key)+ previous = self._queue_metadata_workers.get(context_key)+ if previous is not None:+ previous.controller.stop()+ paths = [path for row, path in enumerate(queue.get_paths())+ if not queue.data(queue.index(row), queue.ThumbnailUrlRole)]+ if not paths:+ return+ images = context_key in {"nr-image", "upscale-image"}++ def task(controller=None) -> None:+ import io+ from PIL import Image+ from ..core.ffmpeg.preview import grab_video_poster_jpeg++ for path_str in paths:+ if controller.cancel.is_set():+ return+ result: dict[str, Any] = {}+ try:+ if images:+ thumbnail = decode_image_preview(path_str)+ width, height = thumbnail.size+ thumbnail.thumbnail((256, 144), Image.Resampling.LANCZOS)+ result = {"width": width, "height": height, "thumbnail": thumbnail}+ else:+ meta = probe_video(path_str, count_mode="metadata", controller=controller)+ result = {"width": meta["width"], "height": meta["height"],+ "duration": meta.get("duration", 0), "frames": meta.get("frames", 0)}+ if controller.cancel.is_set():+ return+ poster = grab_video_poster_jpeg(path_str, max_width=256, controller=controller)+ with Image.open(io.BytesIO(poster)) as image:+ result["thumbnail"] = image.convert("RGB")+ except Exception:+ # An unreadable poster must not prevent the remaining rows loading.+ pass+ if controller.cancel.is_set():+ return+ worker.signals.metadataReady.emit(path_str, result)++ worker = JobWorker(task)+ self._queue_metadata_workers[context_key] = worker++ def ready(path_str: str, result: dict[str, Any]) -> None:+ if self._shutting_down or self._queue_metadata_workers.get(context_key) is not worker:+ return+ try:+ row = queue.get_paths().index(path_str)+ except ValueError:+ return+ width, height = result.get("width", 0), result.get("height", 0)+ thumbnail = result.get("thumbnail")+ url = None+ if thumbnail is not None:+ digest = hashlib.sha1(path_str.encode("utf-8", "surrogatepass")).hexdigest()[:16]+ image_id = f"queue-{context_key}-{digest}"+ self._image_provider.set_image(image_id, thumbnail)+ url = f"image://preview/{image_id}"+ queue.update_metadata(row, input_dimensions=f"{width}×{height}" if width and height else None,+ thumbnail_url=url, duration_seconds=result.get("duration"),+ frame_count=result.get("frames"))++ def finished(*_args) -> None:+ if self._queue_metadata_workers.get(context_key) is worker:+ self._queue_metadata_workers.pop(context_key, None)++ worker.signals.metadataReady.connect(ready)+ worker.signals.finished.connect(finished)+ worker.signals.failed.connect(finished)+ worker.signals.cancelled.connect(finished)self._thread_pool.start(worker)@Slot(int)@@ -3139,7 +3540,7 @@ class AppBridge(QObject):@Slot(int)def selectQueueItem(self, row: int) -> None:if self._operation_state != IDLE:- self._status_message = "Selection changes are disabled while an operation is active."+ self._status_message = UiMessage("Selection changes are disabled while an operation is active.")self.statusMessageChanged.emit()returnqueue = self._active_queue()@@ -3153,7 +3554,7 @@ class AppBridge(QObject):@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._status_message = UiMessage("Queue changes are disabled while an operation is active.")self.statusMessageChanged.emit()returnqueue = self._active_queue()@@ -3168,7 +3569,7 @@ class AppBridge(QObject):@Slot()def clearActiveQueue(self) -> None:if not self.canModifyQueue:- self._status_message = "Queue changes are disabled while an operation is active."+ self._status_message = UiMessage("Queue changes are disabled while an operation is active.")self.statusMessageChanged.emit()returnkey = self._context_key()@@ -3184,13 +3585,13 @@ class AppBridge(QObject):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._status_message = UiMessage("Queue changes are disabled while an operation is active.")self.statusMessageChanged.emit()returnqueue = self._active_queue()row = queue.selectedIndexif not (0 <= row < queue.count):- self._status_message = "No file is selected to clear."+ self._status_message = UiMessage("No file is selected to clear.")self.statusMessageChanged.emit()returnself.removeQueueItem(row)@@ -3215,12 +3616,12 @@ class AppBridge(QObject):except Exception:selected = ""if not selected:- self._status_message = "No file is selected to show in Explorer."+ self._status_message = UiMessage("No file is selected to show in Explorer.")self.statusMessageChanged.emit()returnpath = Path(selected)if not path.is_file():- self._status_message = f"File no longer exists: {path.name}"+ self._status_message = UiMessage("File no longer exists: %1", path.name)self.statusMessageChanged.emit()returntry:@@ -3256,12 +3657,12 @@ class AppBridge(QObject):from PySide6.QtCore import QUrl as _QUrlQDesktopServices.openUrl(_QUrl.fromLocalFile(str(parent)))- self._status_message = f"Opened containing folder for {path.name}."+ self._status_message = UiMessage("Opened containing folder for %1.", path.name)self.statusMessageChanged.emit()returnexcept Exception:pass- self._status_message = f"Could not show in Explorer: {exc}"+ self._status_message = UiMessage("Could not show in Explorer: %1", exc)self.statusMessageChanged.emit()@Slot()@@ -3289,6 +3690,7 @@ class AppBridge(QObject):def _clear_output_preview(self, key: str) -> None:"""Drop an output made with a different scale method, mode, or preset."""+ self._set_preview_error("", key)context = self._contexts[key]if not context.has_output:return@@ -3346,6 +3748,7 @@ class AppBridge(QObject):context.output_height = 0context.preview_source_seconds = 0.0context.preview_source_frame = 0+ context.preview_error = ""context.last_playhead_seconds = 0.0context.rendered_ranges = []context.poster_url = ""@@ -3365,7 +3768,7 @@ class AppBridge(QObject):except Exception:pass- operation_id = self._set_operation(LOADING_METADATA, "Loading media…")+ operation_id = self._set_operation(LOADING_METADATA, UiMessage("Loading media…"))accepts_images = context_key in {"nr-image", "upscale-image"}def task(controller=None, progress=None) -> dict[str, Any]:@@ -3435,7 +3838,12 @@ class AppBridge(QObject):ctx.input_url = f"image://preview/{image_id}?g={generation}"ctx.input_is_video = Falsectx.input_info = f"{path.name} | {dimensions}" if dimensions else path.name- queue.update_metadata(row, input_dimensions=dimensions, thumbnail_url=ctx.input_url)+ thumbnail = result["preview"].copy()+ thumbnail.thumbnail((256, 144))+ thumbnail_id = f"queue-{context_key}-{digest}"+ self._image_provider.set_image(thumbnail_id, thumbnail)+ queue.update_metadata(row, input_dimensions=dimensions,+ thumbnail_url=f"image://preview/{thumbnail_id}")else:ctx.input_url = QUrl.fromLocalFile(str(path)).toString()ctx.input_is_video = True@@ -3446,7 +3854,8 @@ class AppBridge(QObject):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)+ queue.update_metadata(row, input_dimensions=dimensions, duration_seconds=dur,+ frame_count=int((result.get("meta") or {}).get("frames") or 0))poster_jpeg = result.get("poster_jpeg")if poster_jpeg:try:@@ -3456,12 +3865,18 @@ class AppBridge(QObject):poster_id = f"poster-{context_key}"self._image_provider.set_image(poster_id, pil)ctx.poster_url = f"image://preview/{poster_id}?g={generation}"+ digest = hashlib.sha1(str(path).encode("utf-8", "surrogatepass")).hexdigest()[:16]+ thumbnail = pil.copy()+ thumbnail.thumbnail((256, 144))+ thumbnail_id = f"queue-{context_key}-{digest}"+ self._image_provider.set_image(thumbnail_id, thumbnail)+ queue.update_metadata(row, thumbnail_url=f"image://preview/{thumbnail_id}")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."):+ if self._finish_operation(operation_id, UiMessage("Ready.")):self._schedule_auto_preview(140)def failed(message: str) -> None:@@ -3469,18 +3884,19 @@ class AppBridge(QObject):returnself._metadata_worker = Nonectx = self._contexts[context_key]+ ctx.preview_error = messagectx.input_url = QUrl.fromLocalFile(str(path)).toString()ctx.input_is_video = context_key not in {"nr-image", "upscale-image"}ctx.input_info = path.nameif context_key == self._context_key():self._emit_context()- self._finish_operation(operation_id, f"Metadata unavailable for {path.name}.")+ self._finish_operation(operation_id, UiMessage("Metadata unavailable for %1.", 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."))+ worker.signals.cancelled.connect(lambda: self._finish_operation(operation_id, UiMessage("Media loading cancelled.")))self._thread_pool.start(worker)# =========================================================================@@ -3495,11 +3911,11 @@ class AppBridge(QObject):def requestActiveBatchExport(self) -> bool:context_key = self._context_key()if context_key not in {"nr-image", "nr-video", "upscale-image", "upscale-video", "fi-video"} or self._active_tab not in {"neural-rendering", "upscale", "frame-interpolation"}:- self._status_message = "Select a batch processing tab before exporting."+ self._status_message = UiMessage("Select a batch processing tab before exporting.")elif self._operation_state != IDLE or self._runtime_state != "Ready" or self._is_live_running:- self._status_message = "Stop the current operation before starting a batch."+ self._status_message = UiMessage("Stop the current operation before starting a batch.")elif not self._active_queue().get_paths():- self._status_message = "No files in queue to process."+ self._status_message = UiMessage("No files in queue to process.")else:self.batchExportRequested.emit(context_key)return True@@ -3568,7 +3984,7 @@ class AppBridge(QObject):self._export_folder = folderself._ui_settings.setValue("export/destinationMode", destination_mode)if destination_mode == "folder":- self._ui_settings.setValue("export/folder", folder)+ self._ui_settings.setValue("export/folder", encode_app_path(folder))self._ui_settings.sync()self.exportPrefsChanged.emit()@@ -3578,7 +3994,7 @@ class AppBridge(QObject):self.overallProgressChanged.emit()context_key = self._context_key()settings = self._settings- operation_id = self._set_operation(BATCH_PREPARING, "Preparing batch processing…")+ operation_id = self._set_operation(BATCH_PREPARING, UiMessage("Preparing batch processing…"))try:if context_key == "nr-image":@@ -3596,12 +4012,12 @@ class AppBridge(QObject):else:raise RuntimeError("This workspace does not support batch rendering.")except Exception as exc:- self._finish_operation(operation_id, f"Cannot start batch: {exc}")+ self._finish_operation(operation_id, UiMessage("Cannot start batch: %1", exc))return f"Cannot start batch: {exc}"try:self._setup_worker(worker, queue, operation_id, context_key)except Exception as exc:- self._finish_operation(operation_id, f"Cannot start batch: {exc}")+ self._finish_operation(operation_id, UiMessage("Cannot start batch: %1", exc))return f"Cannot start batch: {exc}"return ""@@ -3640,28 +4056,28 @@ class AppBridge(QObject):self._overall_progress = 1.0 if not cancelled else self._overall_progressself.overallProgressChanged.emit()if cancelled:- message = f"Batch cancelled: {len(successes)} completed, {len(failures)} failed/skipped."+ message = UiMessage("Batch cancelled: %1 completed, %2 failed/skipped.", len(successes), len(failures))elif failures:- message = f"Completed with warnings: {len(successes)} completed, {len(failures)} failed."+ message = UiMessage("Completed with warnings: %1 completed, %2 failed.", len(successes), len(failures))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."+ message = UiMessage("Batch complete: %1 completed.", len(successes) or len(queue.get_paths()))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}"+ message = UiMessage("Batch failed: %1", 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."+ message = UiMessage("Batch stopped by user.")self._finish_operation(operation_id, message)self._log(message)@@ -3751,7 +4167,7 @@ class AppBridge(QObject):dlss_mode=settings.nr_dlss_mode,dlss_preset=settings.nr_dlss_preset,codec=settings.codec,- container=container_for_codec(settings.codec),+ container=resolve_container(settings.codec, settings.container),quality=settings.quality,preserve_hdr=coerce_hdr_mode(settings.codec, settings.hdr_mode),rename_mode=settings.video_rename_mode,@@ -3782,7 +4198,7 @@ class AppBridge(QObject):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),+ container=resolve_container(settings.frame_interpolation_codec, settings.frame_interpolation_container),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,@@ -3797,19 +4213,19 @@ class AppBridge(QObject):self._operation_state = PREVIEW_CANCELLINGself.operationStateChanged.emit()self._active_worker.controller.stop()- self._status_message = "Cancelling preview…"+ self._status_message = UiMessage("Cancelling preview…")self.statusMessageChanged.emit()returnif self._operation_state in {BATCH_PREPARING, BATCH_RUNNING} and self._active_worker is not None:self._operation_state = BATCH_CANCELLINGself.operationStateChanged.emit()self._active_worker.controller.stop()- self._status_message = "Cancelling current batch…"+ self._status_message = UiMessage("Cancelling current batch…")self.statusMessageChanged.emit()self._log("User requested batch cancellation.")returnif self._operation_state in {LIVE_STARTING, LIVE_RUNNING}:- self._status_message = "Stopping Live session…"+ self._status_message = UiMessage("Stopping Live session…")self.statusMessageChanged.emit()self.stopLive()return@@ -3858,6 +4274,8 @@ class AppBridge(QObject):raw_seconds = max(0.0, float(position_ms or 0.0) / 1000.0)except (TypeError, ValueError):raw_seconds = 0.0+ if not math.isfinite(raw_seconds):+ raw_seconds = 0.0ctx = self._context()try:fps = float(ctx.source_fps or 0.0)@@ -3869,10 +4287,10 @@ class AppBridge(QObject):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.+ # Clamp the frame index at EOS. Subtracting a fixed time margin here+ # would silently select the penultimate frame at common frame rates.if duration > 0:- raw_seconds = min(raw_seconds, max(0.0, duration - 0.05))+ raw_seconds = min(raw_seconds, duration)total_frames = max(0, int(round(duration * fps))) if duration > 0 else 0frame_index = int(math.floor(raw_seconds * fps)) + 1if total_frames > 0:@@ -3880,8 +4298,6 @@ class AppBridge(QObject):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)@@ -3917,6 +4333,7 @@ class AppBridge(QObject):"""if (self._shutting_down+ or self.lutAutoBusyor not self._auto_preview_enabledor self._runtime_state != "Ready"or self._is_live_running@@ -3924,6 +4341,8 @@ class AppBridge(QObject):returnif self._context_key() not in {"nr-video", "upscale-video"}:return+ if self._skip_unprocessed_preview():+ returnif self._context_key() == "nr-video" and "frame_generation" in enabled_stages(self._settings, "Video"):returnctx = self._context()@@ -3938,6 +4357,16 @@ class AppBridge(QObject):if self._operation_state in {BATCH_PREPARING, BATCH_RUNNING, BATCH_CANCELLING,LIVE_STARTING, LIVE_RUNNING, LIVE_STOPPING}:return+ start_seconds, _ = self._quantize_playhead(position_ms)+ if (self._context_key() == "nr-video" and self._operation_state == IDLE+ and self._has_current_preview("nr-video", start_seconds=start_seconds)):+ # Several transport gestures can address the same nominal frame.+ # Reuse its completed preview instead of decoding/rendering it again.+ self._auto_preview_pending = False+ self._auto_preview_timer.stop()+ self._scrub_pending_pos = None+ self._scrub_preview_timer.stop()+ returntry:self._scrub_pending_pos = max(0.0, float(position_ms or 0.0))except (TypeError, ValueError):@@ -3960,6 +4389,7 @@ class AppBridge(QObject):"""Launch the debounced scrub-refresh render, if still applicable."""if (self._shutting_down+ or self.lutAutoBusyor not self._auto_preview_enabledor self._runtime_state != "Ready"or self._is_live_running@@ -3978,6 +4408,8 @@ class AppBridge(QObject):if self._context_key() not in {"nr-video", "upscale-video"}:self._scrub_pending_pos = Nonereturn+ if self._skip_unprocessed_preview():+ returnctx = self._context()if not ctx.has_output:self._scrub_pending_pos = None@@ -4029,14 +4461,19 @@ class AppBridge(QObject):def _render_preview_impl(self, start_seconds: float = 0.0, frame_index: int = 1,*, clip_seconds: float | None = None) -> None:+ if self._skip_unprocessed_preview():+ if self._operation_state == IDLE:+ self._status_message = UiMessage("Ready.")+ self.statusMessageChanged.emit()+ returnif not self.canPreview:- self._status_message = "Preview is unavailable while another operation is active."+ self._status_message = UiMessage("Preview is unavailable while another operation is active.")self.statusMessageChanged.emit()returnqueue = self._active_queue()source = queue.selected_path()if not source:- self._status_message = "Add and select a file first to preview."+ self._status_message = UiMessage("Add and select a file first to preview.")self.statusMessageChanged.emit()return@@ -4045,6 +4482,7 @@ class AppBridge(QObject):self._preview_generation += 1generation = self._preview_generationcontext.generation = generation+ self._set_preview_error("", context_key)# 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.@@ -4053,7 +4491,7 @@ class AppBridge(QObject):# 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)+ preview_fingerprint = self._auto_preview_fingerprint(context_key, start_seconds=start_seconds)is_video_context = context_key in {"nr-video", "upscale-video", "fi-video"}try:_fps = float(context.source_fps or 0.0)@@ -4079,7 +4517,7 @@ class AppBridge(QObject):else:stamp_label = ""self._active_preview_fast_color = fast_color- operation_id = self._set_operation(PREVIEW_PREPARING, f"Rendering preview{stamp_label}…")+ operation_id = self._set_operation(PREVIEW_PREPARING, UiMessage("Rendering preview%1…", 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@@ -4130,19 +4568,17 @@ class AppBridge(QObject):source, settings, "Video", output_dir=self._preview_cache,controller=controller, progress=progress,start_seconds=start_seconds, clip_seconds=clip_seconds)- result_kind = "video"+ result_kind = "video_still" if clip_seconds is None else "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=clip_seconds is None, progress=progress,controller=controller, output_dir=self._preview_cache,- preview_encoding=settings.preview_encoding,start_seconds=start_seconds, frame_index=frame_index,preview_seconds=clip_seconds,)- result_kind = "video"+ result_kind = "video_still" if clip_seconds is None else "video"elif context_key == "fi-video":opts = FrameInterpolationOptions(ai_gpu_uuid=settings.ai_gpu_uuid,@@ -4150,13 +4586,13 @@ class AppBridge(QObject):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),+ container=resolve_container(settings.frame_interpolation_codec, settings.frame_interpolation_container),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,+ source, opts,progress=progress, output_dir=self._preview_cache,controller=controller, start_seconds=start_seconds,frame_index=frame_index,@@ -4166,7 +4602,9 @@ class AppBridge(QObject):else:raise RuntimeError("Preview is unavailable for this workspace.")except Exception as exc:- self._finish_operation(operation_id, f"Preview configuration error: {exc}")+ self._set_preview_error(str(exc), context_key)+ self._finish_operation(operation_id, UiMessage("Preview configuration error: %1", exc))+ self._log(self._status_message)returnworker = JobWorker(task)@@ -4186,7 +4624,7 @@ class AppBridge(QObject):if operation_id != self._operation_id:returnif generation != self._contexts[context_key].generation:- self._finish_operation(operation_id, "Preview superseded by newer settings.")+ self._finish_operation(operation_id, UiMessage("Preview superseded by newer settings."))if self._auto_preview_pending:self._auto_preview_timer.start(80)return@@ -4254,7 +4692,7 @@ class AppBridge(QObject):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}.")+ self._finish_operation(operation_id, UiMessage("Preview complete%1.", stamp_label))if status:for line in str(status).splitlines():line = line.strip()@@ -4265,6 +4703,8 @@ class AppBridge(QObject):if operation_id != self._operation_id:returntext = f"Preview failed: {message}"+ if generation == self._contexts[context_key].generation:+ self._set_preview_error(text, context_key)self._finish_operation(operation_id, text)self._log(text)if self._auto_preview_pending:@@ -4273,7 +4713,7 @@ class AppBridge(QObject):def cancelled() -> None:if operation_id != self._operation_id:return- self._finish_operation(operation_id, "Preview cancelled.")+ self._finish_operation(operation_id, UiMessage("Preview cancelled."))if self._auto_preview_pending:self._auto_preview_timer.start(80)@@ -4299,31 +4739,31 @@ class AppBridge(QObject):buffer_seconds: float,) -> None:if not self.canStartLive:- self._live_status_text = "Live is unavailable while another operation is active."+ self._live_status_text = UiMessage("Live is unavailable while another operation is active.")self.liveStatusTextChanged.emit()returnif 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._live_status_text = UiMessage("Select a valid local video file.")self.liveStatusTextChanged.emit()returntry: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._live_status_text = UiMessage("Select a valid local video file (MP4/MKV/MOV/AVI/WebM...).")self.liveStatusTextChanged.emit()returnexcept 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._live_status_text = UiMessage("Select a valid local video file (MP4/MKV/MOV/AVI/WebM...).")self.liveStatusTextChanged.emit()returnselected_source = cleanedelse:selected_source = online_url.strip()if not selected_source:- self._live_status_text = "Enter a valid online URL (Twitch, YouTube, HLS, etc.)."+ self._live_status_text = UiMessage("Enter a valid online URL (Twitch, YouTube, HLS, etc.).")self.liveStatusTextChanged.emit()return@@ -4376,7 +4816,7 @@ class AppBridge(QObject):source_quality=source_quality,)except Exception as exc:- self._live_status_text = f"Invalid Live configuration: {exc}"+ self._live_status_text = UiMessage("Invalid Live configuration: %1", exc)self.liveStatusTextChanged.emit()return@@ -4384,8 +4824,8 @@ class AppBridge(QObject):self._is_live_starting = Trueself._stop_live_after_start = Falseself.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…"+ operation_id = self._set_operation(LIVE_STARTING, UiMessage("Resolving source and starting Live pipeline…"))+ self._live_status_text = UiMessage("Resolving source and starting Live pipeline…")self.liveStatusTextChanged.emit()worker = JobWorker(lambda: start_live_session(opts), inject_callbacks=False)@@ -4403,11 +4843,11 @@ class AppBridge(QObject):self._stop_live_after_start = Falseself.stopLive()return- self._live_status_text = getattr(info, "status", "Live session started.")+ self._live_status_text = UiMessage(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.")+ self._finish_operation(operation_id, UiMessage("Live session running."))else:self._finish_operation(operation_id, self._live_status_text)self._log(f"Live session started: {selected_source}")@@ -4419,7 +4859,7 @@ class AppBridge(QObject):self._is_live_starting = Falseself._is_live_running = Falseself._stop_live_after_start = False- self._live_status_text = f"Live failed: {message}"+ self._live_status_text = UiMessage("Live failed: %1", message)self.isLiveStartingChanged.emit()self.isLiveRunningChanged.emit()self.liveStatusTextChanged.emit()@@ -4442,9 +4882,9 @@ class AppBridge(QObject):# 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._live_status_text = UiMessage("Cancel requested; stopping as soon as Live finishes starting…")self.liveStatusTextChanged.emit()- self._status_message = "Cancelling Live startup…"+ self._status_message = UiMessage("Cancelling Live startup…")self.statusMessageChanged.emit()returnif not (self._is_live_running or is_live_running()):@@ -4453,8 +4893,8 @@ class AppBridge(QObject):returnself._live_timer.stop()- operation_id = self._set_operation(LIVE_STOPPING, "Stopping Live session…")- self._live_status_text = "Stopping Live session…"+ operation_id = self._set_operation(LIVE_STOPPING, UiMessage("Stopping Live session…"))+ self._live_status_text = UiMessage("Stopping Live session…")self.liveStatusTextChanged.emit()worker = JobWorker(stop_live_session, inject_callbacks=False)self._live_worker = worker@@ -4466,7 +4906,7 @@ class AppBridge(QObject):self._is_live_starting = Falseself._is_live_running = Falseself._live_effects_dirty = False- self._live_status_text = getattr(info, "status", "Stopped.")+ self._live_status_text = UiMessage(getattr(info, "status", "Stopped."))self.isLiveStartingChanged.emit()self.isLiveRunningChanged.emit()self.liveStatusTextChanged.emit()@@ -4474,7 +4914,7 @@ class AppBridge(QObject):self._mpv_embed.set_session_active(False)except Exception:pass- self._finish_operation(operation_id, "Live session stopped.")+ self._finish_operation(operation_id, UiMessage("Live session stopped."))self._log("Live session stopped.")def failed(message: str) -> None:@@ -4483,7 +4923,7 @@ class AppBridge(QObject):self._live_worker = Noneself._is_live_starting = Falseself._is_live_running = bool(is_live_running())- self._live_status_text = f"Stop error: {message}"+ self._live_status_text = UiMessage("Stop error: %1", message)self.isLiveStartingChanged.emit()self.isLiveRunningChanged.emit()self.liveStatusTextChanged.emit()@@ -4534,28 +4974,29 @@ class AppBridge(QObject):self._mpv_embed.set_session_active(False)except Exception:pass- parts = [info.status]+ parts = [UiMessage(info.status)]if info.playlist_url:- parts.append(f"Playlist: {info.playlist_url}")+ parts.append(UiMessage("Playlist: %1", 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"+ UiMessage("MPV: %1 dropped, %2 rebuffer events, A/V sync %3 ms",+ info.player_dropped_frames, info.rebuffer_events, f"{info.av_sync_ms:+.1f}"))if info.output_size:parts.append(- f"Received {info.source_size} -> Input {info.input_size} -> "- f"Output {info.output_size} | {info.encoder}"+ UiMessage("Received %1 → Input %2 → Output %3 (%4)",+ info.source_size, info.input_size, info.output_size, info.encoder))if info.source_quality_note:parts.append(info.source_quality_note)- parts.append(f"DLSS effects: {info.effects_status}")+ parts.append(UiMessage("DLSS effects: %1", UiMessage(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"+ UiMessage("Source: %1 fps, Guide: %2 ms, DLSS: %3 ms, Encode: %4 ms",+ f"{info.source_fps:.1f}", f"{info.guide_ms:.1f}",+ f"{info.dlss_ms:.1f}", f"{info.encode_ms:.1f}"))- self._live_status_text = "\n".join(parts)+ self._live_status_text = join_messages(parts)self.liveStatusTextChanged.emit()if not self._is_live_running:self._live_timer.stop()@@ -4587,7 +5028,8 @@ class AppBridge(QObject):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, self._lut_save_worker, self._lut_auto_worker):+ self._live_worker, self._lut_save_worker, self._lut_auto_worker,+ self._lut_reference_worker, *self._queue_metadata_workers.values()):if worker is not None:try:worker.controller.stop()@@ -4655,7 +5097,7 @@ class AppBridge(QObject):clipboard = QGuiApplication.clipboard()if clipboard is not None:clipboard.setText(text)- self._status_message = "Copied to clipboard."+ self._status_message = UiMessage("Copied to clipboard.")self.statusMessageChanged.emit()@staticmethod@@ -4915,7 +5357,7 @@ class AppBridge(QObject):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…")+ operation_id = self._set_operation(SCANNING_INPUTS, UiMessage("Downloading web image…"))worker = JobWorker(self._fetch_first_remote_paste_image,list(candidates),@@ -4929,25 +5371,25 @@ class AppBridge(QObject):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…"):+ if not self._finish_operation(operation_id, UiMessage("Download complete. Scanning…")):returntry:self._paste_select_single = Trueself.addFiles([QUrl.fromLocalFile(str(local_path)).toString()])except Exception as exc:- self._status_message = f"Paste failed: {exc}"+ self._status_message = UiMessage("Paste failed: %1", 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._finish_operation(operation_id, UiMessage("Web image download failed: %1", 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.")+ lambda: self._finish_operation(operation_id, UiMessage("Download cancelled.")))self._thread_pool.start(worker)@@ -4966,7 +5408,7 @@ class AppBridge(QObject):if self._active_tab not in {"neural-rendering", "upscale", "frame-interpolation"}:returnif not self.canModifyQueue:- self._status_message = "Queue changes are disabled while an operation is active."+ self._status_message = UiMessage("Queue changes are disabled while an operation is active.")self.statusMessageChanged.emit()returntry:@@ -5023,7 +5465,7 @@ class AppBridge(QObject):self._paste_select_single = Trueself.addFiles(local_urls)except Exception as exc:- self._status_message = f"Paste failed: {exc}"+ self._status_message = UiMessage("Paste failed: %1", exc)self.statusMessageChanged.emit()self._log(f"Paste failed: {exc}")return@@ -5063,7 +5505,7 @@ class AppBridge(QObject):formats = list(mime.formats() or [])[:12]except Exception:formats = []- self._status_message = "Clipboard has no images or files to paste."+ self._status_message = UiMessage("Clipboard has no images or files to paste.")self.statusMessageChanged.emit()self._log(f"Paste found no usable data (formats: {formats}).")diff --git a/src/desktop/cas_sharpening.py b/src/desktop/cas_sharpening.pyindex af73566..9731db9 100644--- a/src/desktop/cas_sharpening.py+++ b/src/desktop/cas_sharpening.py@@ -1,235 +1,75 @@-"""File-backed sharpening stage with FidelityFX CAS and NVIDIA NVSharpen.--The CAS core below is a CPU implementation of the default no-scaling path in-``native (dev)/FidelityFX-SDK-v1.1.4/sdk/include/FidelityFX/gpu/cas/ffx_cas.h``.-It uses the SDK's sharpness constant, cross-neighbour soft min/max and green-channel weight. The SDK's D3D12/Vulkan dispatcher is designed for a GPU render-graph; this file-backed stage applies that pixel math to decoded RGB frames-and blends the result by the user-facing percentage. NVIDIA NVSharpen is-implemented separately in ``nis_sharpening.py`` and selected here at runtime.-"""--# CAS algorithm derived from FidelityFX SDK 1.1.4.-# Copyright (C) 2024 Advanced Micro Devices, Inc.-# See AMD-FidelityFX-CAS-LICENSE.txt in this directory.--from __future__ import annotations--from fractions import Fraction-from pathlib import Path-from typing import Callable--import av-import numpy as np-+"""File-backed Vulkan CAS and NIS sharpening stages."""+from __future__ import annotations++from pathlib import Path+from typing import Callable++import numpy as np+from ..core import ffmpeg-from ..core.jobs import Cancelled, JobController-from ..neural_rendering.image.decoder import decode_image-from ..neural_rendering.image.encoder import _encode_image-from ..neural_rendering.image.models import ImageConversionOptions-from ..settings.models import UISettings-from .nis_sharpening import sharpen_rgb as nis_sharpen_rgb---def _linearize(value: np.ndarray, transfer: str) -> np.ndarray:- if transfer == "srgb":- return np.where(value <= 0.04045, value / 12.92,- ((value + 0.055) / 1.055) ** 2.4)- if transfer == "bt709":- return np.where(value < 0.081, value / 4.5,- ((value + 0.099) / 1.099) ** (1.0 / 0.45))- return value---def _encode_transfer(value: np.ndarray, transfer: str) -> np.ndarray:- if transfer == "srgb":- return np.where(value <= 0.0031308, value * 12.92,- 1.055 * np.power(value, 1.0 / 2.4) - 0.055)- if transfer == "bt709":- return np.where(value < 0.018, value * 4.5,- 1.099 * np.power(value, 0.45) - 0.099)- return value---def sharpen_rgb(pixels: np.ndarray, sharpness: int, *, transfer: str = "srgb",- alpha: np.ndarray | None = None,- controller: JobController | None = None) -> np.ndarray:- """Apply the SDK's sharpen-only CAS filter to 8/16-bit RGB pixels.-- 0% is an application-level bypass. In the SDK, sharpness=0 still applies- its baseline filter, so the filtered result is blended by the UI strength- for a smooth transition from an untouched input to SDK maximum sharpness.- Alpha is not filtered. Semi-transparent pixels and their opaque neighbours- are left alone to keep hidden RGB from causing edge halos.- """- if pixels.ndim != 3 or pixels.shape[2] != 3 or pixels.dtype not in (np.uint8, np.uint16):- raise ValueError("CAS requires an 8-bit or 16-bit RGB image.")- if isinstance(sharpness, bool) or not isinstance(sharpness, int) or not 0 <= sharpness <= 100:- raise ValueError("CAS sharpness must be an integer from 0 to 100.")- if alpha is not None and (alpha.shape != pixels.shape[:2] or alpha.dtype != pixels.dtype):- raise ValueError("CAS alpha must match the RGB pixels.")- if transfer not in {"srgb", "bt709", "linear"}:- raise ValueError("Unsupported CAS transfer function.")- if sharpness == 0 or min(pixels.shape[:2]) < 2:- return pixels.copy()-- height, width = pixels.shape[:2]- maximum = float(np.iinfo(pixels.dtype).max)- mix = sharpness / 100.0- peak = -1.0 / (8.0 - 3.0 * sharpness / 100.0) # ffxCasSetup()- result = np.empty_like(pixels)- tile = 256 # Keep 4K/16-bit intermediates bounded while retaining a 1px halo.-- for y in range(0, height, tile):- for x in range(0, width, tile):- if controller is not None and controller.cancel.is_set():- raise Cancelled("Render stopped by user.")- bottom, right = min(height, y + tile), min(width, x + tile)- y0, y1 = max(0, y - 1), min(height, bottom + 1)- x0, x1 = max(0, x - 1), min(width, right + 1)- border = ((int(y == 0), int(bottom == height)),- (int(x == 0), int(right == width)))- block = np.pad(pixels[y0:y1, x0:x1], (*border, (0, 0)), mode="edge")- block = block.astype(np.float32) / maximum- block = _linearize(block, transfer)- b = block[:-2, 1:-1]- d = block[1:-1, :-2]- e = block[1:-1, 1:-1]- f = block[1:-1, 2:]- h = block[2:, 1:-1]-- minimum = np.minimum(np.minimum(np.minimum(d, e), f), np.minimum(b, h))- maximum_rgb = np.maximum(np.maximum(np.maximum(d, e), f), np.maximum(b, h))- # The SDK computes each channel's amplification, then uses only- # green's weight for all output channels.- green_min = minimum[..., 1]- green_max = maximum_rgb[..., 1]- amplification = np.sqrt(np.clip(- np.minimum(green_min, 1.0 - green_max) /- np.maximum(green_max, np.finfo(np.float32).tiny), 0.0, 1.0))- weight = amplification * peak- if alpha is not None:- a = np.pad(alpha[y0:y1, x0:x1], border, mode="edge")- fully_opaque = ((a[1:-1, 1:-1] == maximum) &- (a[:-2, 1:-1] == maximum) &- (a[1:-1, :-2] == maximum) &- (a[1:-1, 2:] == maximum) &- (a[2:, 1:-1] == maximum))- weight = np.where(fully_opaque, weight, 0.0)- filtered = np.clip((e + weight[..., None] * (b + d + f + h)) /- (1.0 + 4.0 * weight[..., None]), 0.0, 1.0)- filtered = e + mix * (filtered - e)- filtered = np.clip(_encode_transfer(filtered, transfer), 0.0, 1.0)- result[y:bottom, x:right] = np.rint(filtered * maximum).astype(pixels.dtype)- return result---def _selected_sharpen(pixels: np.ndarray, settings: UISettings, *, transfer: str,- alpha: np.ndarray | None = None,- controller: JobController | None = None) -> np.ndarray:- if settings.sharpening_method == "NVIDIA NIS":- return nis_sharpen_rgb(pixels, settings.cas_sharpness,- alpha=alpha, controller=controller)- if settings.sharpening_method == "AMD CAS":- return sharpen_rgb(pixels, settings.cas_sharpness, transfer=transfer,- alpha=alpha, controller=controller)- raise ValueError(f"Unknown sharpening method: {settings.sharpening_method!r}.")---def sharpen_image(source: Path, settings: UISettings, directory: Path,- controller: JobController, progress: Callable) -> Path:- if settings.cas_sharpness == 0:- progress(1.0, "Sharpening complete")- return source- decoded = decode_image(source)- progress(0.1, "Sharpening image")- rgba = decoded.rgba- rgba[..., :3] = _selected_sharpen(rgba[..., :3], settings, transfer="srgb",- alpha=decoded.alpha, controller=controller)- if controller.cancel.is_set():- raise Cancelled("Render stopped by user.")- output = directory / "sharpened.tiff"- progress(0.85, "Saving sharpened image")- _encode_image(output, rgba,- ImageConversionOptions(output_format="TIFF", preserve_metadata=False),- {}, generate_preview=False, controller=controller,- has_transparency=decoded.alpha is not None)- progress(1.0, "Sharpening complete")- return output---def sharpen_video(source: Path, settings: UISettings, directory: Path,- controller: JobController, progress: Callable) -> Path:- if settings.cas_sharpness == 0:- progress(1.0, "Sharpening complete")- return source- metadata = ffmpeg.probe_video(source, count_mode="metadata", controller=controller)- if metadata.get("hdr"):- raise ValueError("Sharpening requires SDR video at this position. Move it before HDR conversion.")- transfer = {"iec61966-2-1": "srgb", "linear": "linear"}.get(- metadata.get("color_transfer"), "bt709")- output = directory / "sharpened.mkv"- input_container = av.open(str(source))- output_container = None- try:- input_stream = input_container.streams.video[0]- input_stream.thread_type = "AUTO"- rate = input_stream.average_rate or Fraction(30, 1)- time_base = input_stream.time_base or Fraction(1, max(1, round(float(rate))))- output_container = av.open(str(output), mode="w")- output_stream = output_container.add_stream("ffv1", rate=rate)- output_stream.width = input_stream.width- output_stream.height = input_stream.height- output_stream.pix_fmt = "gbrp10le"- if input_stream.sample_aspect_ratio is not None:- output_stream.sample_aspect_ratio = input_stream.sample_aspect_ratio- output_stream.time_base = time_base- output_stream.codec_context.time_base = time_base- output_stream.codec_context.colorspace = 0 # GBR- output_stream.codec_context.color_range = 2 # full range- output_stream.codec_context.color_primaries = input_stream.codec_context.color_primaries or 1- output_stream.codec_context.color_trc = input_stream.codec_context.color_trc or 1- output_stream.metadata.update(input_stream.metadata)- output_stream.codec_context.open()- estimated = int(metadata.get("frames") or 0)- if estimated <= 0:- estimated = max(1, round(float(metadata.get("duration") or 0) * float(rate)))- count = 0- last_pts: int | None = None- frame_step = max(1, round(Fraction(1, 1) / rate / time_base))- for frame in input_container.decode(input_stream):- if controller.cancel.is_set():- raise Cancelled("Render stopped by user.")- if (frame.width, frame.height) != (output_stream.width, output_stream.height):- raise ValueError("Video dimensions changed during sharpening.")- rgb = frame.to_ndarray(format="rgb48le")- filtered = _selected_sharpen(rgb, settings, transfer=transfer,- controller=controller)- processed = av.VideoFrame.from_ndarray(filtered, format="rgb48le")- processed = processed.reformat(format="gbrp10le")- pts = (round(Fraction(frame.pts) * (frame.time_base or time_base) / time_base)- if frame.pts is not None else (last_pts + frame_step if last_pts is not None else 0))- if last_pts is not None and pts <= last_pts:- raise ValueError("Source timestamps are not strictly increasing; Sharpening cannot preserve this video timing.")- processed.pts = pts- processed.time_base = time_base- processed.color_primaries = output_stream.codec_context.color_primaries- processed.color_trc = output_stream.codec_context.color_trc- processed.colorspace = 0- processed.color_range = 2- for packet in output_stream.encode(processed):- output_container.mux(packet)- last_pts = pts- count += 1- if count == 1 or count % 12 == 0:- progress(min(0.95, count / estimated), "Sharpening video")- if not count:- raise ValueError("The input contains no decodable video frames.")- for packet in output_stream.encode():- output_container.mux(packet)- finally:- if output_container is not None:- output_container.close()- input_container.close()- progress(1.0, "Sharpening complete")- return output+from ..core.cache_video import cache_ffmpeg_args, cache_video_format+from ..core.paths import FFMPEG+from ..core.jobs import Cancelled, JobController+from ..neural_rendering.image.decoder import decode_image+from ..neural_rendering.image.encoder import _encode_image+from ..neural_rendering.image.models import ImageConversionOptions+from ..settings.models import UISettings+from ..core.ffmpeg.sharpening import sharpen_rgb, sharpening_filter+from ..core.ffmpeg.vulkan import run as run_vulkan+++def _selected_sharpen(pixels: np.ndarray, settings: UISettings, *, transfer: str,+ alpha: np.ndarray | None = None,+ controller: JobController | None = None) -> np.ndarray:+ if settings.sharpening_method == "NVIDIA NIS":+ return sharpen_rgb(pixels, settings.cas_sharpness, method="NVIDIA NIS",+ alpha=alpha, controller=controller)+ if settings.sharpening_method == "AMD CAS":+ return sharpen_rgb(pixels, settings.cas_sharpness, transfer=transfer,+ alpha=alpha, controller=controller)+ raise ValueError(f"Unknown sharpening method: {settings.sharpening_method!r}.")+++def sharpen_image(source: Path, settings: UISettings, directory: Path,+ controller: JobController, progress: Callable) -> Path:+ if settings.cas_sharpness == 0:+ progress(1.0, "Sharpening complete")+ return source+ decoded = decode_image(source)+ progress(0.1, "Sharpening image")+ rgba = decoded.rgba+ rgba[..., :3] = _selected_sharpen(rgba[..., :3], settings, transfer="srgb",+ alpha=decoded.alpha, controller=controller)+ if controller.cancel.is_set():+ raise Cancelled("Render stopped by user.")+ output = directory / "sharpened.tiff"+ progress(0.85, "Saving sharpened image")+ _encode_image(output, rgba,+ ImageConversionOptions(output_format="TIFF", preserve_metadata=False),+ {}, generate_preview=False, controller=controller,+ has_transparency=decoded.alpha is not None)+ progress(1.0, "Sharpening complete")+ return output+++def sharpen_video(source: Path, settings: UISettings, directory: Path,+ controller: JobController, progress: Callable) -> Path:+ if settings.cas_sharpness == 0:+ progress(1.0, "Sharpening complete")+ return source+ metadata = ffmpeg.probe_video(source, count_mode="metadata", controller=controller)+ if metadata.get("hdr"):+ raise ValueError("Sharpening requires SDR video at this position. Move it before HDR conversion.")+ transfer = {"iec61966-2-1": "srgb", "linear": "linear"}.get(+ metadata.get("color_transfer"), "bt709")+ output = directory / ("sharpened" + cache_video_format(settings.cache_codec)[2])+ progress(0.0, "Sharpening video on Vulkan")+ graph = "ve_gpu," + sharpening_filter(settings.sharpening_method, settings.cas_sharpness, transfer)+ command = [str(FFMPEG), "-v", "error", "-y", "-i", str(source),+ "-map", "0:v:0", "-map_metadata", "0", "-an", "-vf", graph,+ *cache_ffmpeg_args(settings.cache_codec, metadata),+ "-fps_mode", "passthrough", str(output)]+ run_vulkan(command, controller, "Vulkan sharpening", selection=settings.ffmpeg_device,+ progress=progress, metadata=metadata)+ progress(1.0, "Sharpening complete")+ return outputdiff --git a/src/desktop/color_preview.py b/src/desktop/color_preview.pyindex 1108ae9..406c658 100644--- a/src/desktop/color_preview.py+++ b/src/desktop/color_preview.py@@ -1,164 +1,172 @@-"""Low-latency, full-resolution still previews for the Coloring LUT card.--The export pipeline bakes a .cube and writes lossless intermediates. A still-preview can evaluate the same grading function at the source pixels directly:-this avoids the cube bake, intermediate files, and video encoder. The source-frame and its unadjusted LUT sample are reused while sliders move.-"""--from __future__ import annotations-+"""Low-latency, full-resolution still previews for the Coloring LUT card.++The still path avoids lossless video intermediates. Source pixels are reused+while sliders move; the composed export-equivalent cube is reused while the+timeline moves. Both caches are bounded to one entry.+"""++from __future__ import annotations+import subprocess+import tempfileimport threading-from dataclasses import dataclass-from pathlib import Path-+import weakref+from dataclasses import dataclass+from pathlib import Path+import numpy as np-from ..core.jobs import Cancelled-from ..core.paths import FFMPEG-from ..neural_rendering.image.decoder import decode_image-from ..settings.models import UISettings-from .coloring import grade_lut_rgb, load_cube_lut, sample_cube_lut---MAX_PREVIEW_PIXELS = 8_500_000-_MAX_CACHE_BYTES = 320 * 1024 * 1024-_lock = threading.RLock()---@dataclass+from ..core.ffmpeg.vulkan import prepare_command+from ..core.jobs import Cancelled+from ..core.paths import FFMPEG+from ..neural_rendering.image.decoder import decode_image+from ..settings.models import LUT_ADJUSTMENT_RANGES, UISettings+from .coloring import (apply_cube_lut_file, compose_cube_lut, identity_cube_lut,+ load_cube_lut, write_composed_lut)+from .preview_cache import cache_key, file_identity+++MAX_PREVIEW_PIXELS = 8_500_000+_MAX_CACHE_BYTES = 320 * 1024 * 1024+_lock = threading.RLock()+++@dataclassclass _CachedFrame:key: tuplergba: np.ndarray- rgb: np.ndarray- lut_key: tuple | None = None- sampled: np.ndarray | None = None--++_cached_frame: _CachedFrame | None = None-class FastPreviewUnavailable(ValueError):- """Use the file-backed preview when this source cannot use the RAM path."""---def _source_key(source: str | Path, mode: str, start_seconds: float,- size: tuple[int, int] | None) -> tuple:- path = Path(source).resolve()- stat = path.stat()- return (str(path), stat.st_mtime_ns, stat.st_size, mode,- round(float(start_seconds), 6) if mode == "Video" else 0,- size if mode == "Video" else None)-+@dataclass+class _CachedLut:+ key: str+ directory: tempfile.TemporaryDirectory+ path: Path-def _video_frame(path: Path, start_seconds: float, size: tuple[int, int]) -> np.ndarray:- width, height = size- if width <= 0 or height <= 0 or width * height > MAX_PREVIEW_PIXELS:- raise FastPreviewUnavailable("Video dimensions are unavailable for the fast preview.")- # Match the seek used by the lossless clip extractor. ffmpeg converts the- # decoded frame to 16-bit RGBA, so 10-bit source color is not truncated.- start = max(0.0, float(start_seconds) - 0.002)- fast_seek = max(0.0, start - 2.0)- accurate_seek = max(0.0, start - fast_seek)- command = [str(FFMPEG), "-hide_banner", "-loglevel", "error",- "-ss", f"{fast_seek:.6f}", "-i", str(path),- "-ss", f"{accurate_seek:.6f}", "-frames:v", "1", "-an",- "-f", "rawvideo", "-pix_fmt", "rgba64le", "pipe:1"]- result = subprocess.run(- command, capture_output=True, timeout=30, check=False,- creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),- )- if result.returncode != 0:- raise RuntimeError(result.stderr.decode("utf-8", "replace").strip()- or "Could not decode the preview frame.")- if len(result.stdout) != width * height * 8:- raise FastPreviewUnavailable("Decoded frame dimensions differ from the source metadata.")- return np.frombuffer(result.stdout, dtype="<u2").reshape(height, width, 4)+ def __post_init__(self):+ weakref.finalize(self, self.directory.cleanup)-def _frame(key: tuple, size: tuple[int, int] | None) -> _CachedFrame:- global _cached_frame- with _lock:- if _cached_frame is not None and _cached_frame.key == key:- return _cached_frame- path = Path(key[0])- rgba = decode_image(path).rgba if key[3] == "Image" else _video_frame(path, key[4], size)- if rgba.shape[0] * rgba.shape[1] > MAX_PREVIEW_PIXELS:- raise FastPreviewUnavailable("This image is too large for the in-memory preview.")- maximum = np.iinfo(rgba.dtype).max- rgb = rgba[..., :3].astype(np.float32) / float(maximum)- frame = _CachedFrame(key, rgba, rgb)- if rgba.nbytes + rgb.nbytes <= _MAX_CACHE_BYTES:- with _lock:- _cached_frame = frame- return frame+_cached_lut: _CachedLut | None = None-def _lut_sample(frame: _CachedFrame, path: str) -> np.ndarray:- if not path:- return frame.rgb- lut_path = Path(path).resolve()- stat = lut_path.stat()- key = (str(lut_path), stat.st_mtime_ns, stat.st_size)+def _prepared_lut(settings: UISettings, controller=None) -> _CachedLut:+ global _cached_lut+ key = cache_key({"lut": file_identity(settings.lut_path) if settings.lut_path else None,+ "resolution": settings.lut_resolution,+ "adjustments": {field: getattr(settings, field) for field in LUT_ADJUSTMENT_RANGES}})with _lock:- if frame.lut_key == key and frame.sampled is not None:- return frame.sampled- lut = load_cube_lut(lut_path)- # Keep temporary trilinear arrays bounded for large source frames.- sampled = np.empty_like(frame.rgb)- flattened_input = frame.rgb.reshape(-1, 3)- flattened_output = sampled.reshape(-1, 3)- for offset in range(0, len(flattened_input), 262_144):- end = min(len(flattened_input), offset + 262_144)- flattened_output[offset:end] = sample_cube_lut(flattened_input[offset:end], lut)- if frame.rgba.nbytes + frame.rgb.nbytes + sampled.nbytes <= _MAX_CACHE_BYTES:+ if _cached_lut is not None and _cached_lut.key == key and _cached_lut.path.is_file():+ return _cached_lut+ directory = tempfile.TemporaryDirectory(prefix="visual-enhancer-preview-lut-")+ try:+ path = Path(directory.name) / "filter.cube"+ base = load_cube_lut(settings.lut_path) if settings.lut_path else identity_cube_lut()+ lut = compose_cube_lut(base, settings, settings.lut_resolution, controller=controller)+ write_composed_lut(path, lut, controller=controller)+ if controller is not None and controller.cancel.is_set():+ raise Cancelled("Preview superseded by newer settings.")+ prepared = _CachedLut(key, directory, path)with _lock:- frame.lut_key = key- frame.sampled = sampled- return sampled---def render_color_still_preview(source: str | Path, settings: UISettings, mode: str,- *, start_seconds: float = 0.0,- video_size: tuple[int, int] | None = None,- controller=None, progress=None) -> tuple[np.ndarray, str]:- """Grade an image or one video frame in memory at source resolution.-- The selected export LUT resolution affects .cube sampling, not this- evaluation. Evaluating the grading function directly is at least as- accurate as sampling its baked 33/65/129-point approximation.- """- if mode not in {"Image", "Video"}:- raise ValueError("Unsupported coloring preview mode.")- if mode == "Video" and video_size is None:- raise ValueError("Video dimensions are required for the fast preview.")- key = _source_key(source, mode, start_seconds, video_size)- if controller is not None and controller.cancel.is_set():- raise Cancelled("Preview superseded by newer settings.")- frame = _frame(key, video_size)- if progress is not None:- progress(0.35, "Coloring: source frame ready")- if controller is not None and controller.cancel.is_set():- raise Cancelled("Preview superseded by newer settings.")- if settings.lut_mix == 0 and settings.lut_path:- load_cube_lut(settings.lut_path)- sampled = frame.rgb if settings.lut_mix == 0 else _lut_sample(frame, settings.lut_path)- if controller is not None and controller.cancel.is_set():- raise Cancelled("Preview superseded by newer settings.")- maximum = np.iinfo(frame.rgba.dtype).max- result = np.empty_like(frame.rgba)- source_rgb = frame.rgb.reshape(-1, 3)- sampled_rgb = sampled.reshape(-1, 3)- output_pixels = result.reshape(-1, 4)- for offset in range(0, len(source_rgb), 262_144):+ _cached_lut = prepared+ # A caller keeps the entry alive until its GPU command finishes, even+ # if another render replaces the cache. TemporaryDirectory then cleans+ # up the old cube once its last user releases it.+ return prepared+ except BaseException:+ directory.cleanup()+ raise+++class FastPreviewUnavailable(ValueError):+ """Use the file-backed preview when this source cannot use the RAM path."""+++def _source_key(source: str | Path, mode: str, start_seconds: float,+ size: tuple[int, int] | None) -> tuple:+ path = Path(source).resolve()+ stat = path.stat()+ return (str(path), stat.st_mtime_ns, stat.st_size, mode,+ round(float(start_seconds), 6) if mode == "Video" else 0,+ size if mode == "Video" else None)+++def _video_frame(path: Path, start_seconds: float, size: tuple[int, int], controller=None) -> np.ndarray:+ width, height = size+ if width <= 0 or height <= 0 or width * height > MAX_PREVIEW_PIXELS:+ raise FastPreviewUnavailable("Video dimensions are unavailable for the fast preview.")+ # Match the seek used by the lossless clip extractor. ffmpeg converts the+ # decoded frame to 16-bit RGBA, so 10-bit source color is not truncated.+ start = max(0.0, float(start_seconds) - 0.002)+ fast_seek = max(0.0, start - 2.0)+ accurate_seek = max(0.0, start - fast_seek)+ command = [str(FFMPEG), "-hide_banner", "-loglevel", "error",+ "-ss", f"{fast_seek:.6f}", "-i", str(path),+ "-ss", f"{accurate_seek:.6f}", "-frames:v", "1", "-an",+ "-f", "rawvideo", "-pix_fmt", "rgba64le", "pipe:1"]+ command = prepare_command(command)+ process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE,+ creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))+ if controller is not None:+ controller.register(process)+ try:+ pixels, errors = process.communicate(timeout=30)if controller is not None and controller.cancel.is_set():raise Cancelled("Preview superseded by newer settings.")- end = min(len(source_rgb), offset + 262_144)- graded = grade_lut_rgb(source_rgb[offset:end], sampled_rgb[offset:end], settings)- output_pixels[offset:end, :3] = np.rint(- np.clip(graded, 0.0, 1.0) * maximum).astype(frame.rgba.dtype)- result[..., 3] = frame.rgba[..., 3]- if progress is not None:- progress(1.0, "Coloring preview complete")- return result, ""+ if process.returncode != 0:+ raise RuntimeError(errors.decode("utf-8", "replace").strip()+ or "Could not decode the preview frame.")+ if len(pixels) != width * height * 8:+ raise FastPreviewUnavailable("Decoded frame dimensions differ from the source metadata.")+ return np.frombuffer(pixels, dtype="<u2").reshape(height, width, 4)+ finally:+ if process.poll() is None:+ process.kill()+ process.communicate()+ if controller is not None:+ controller.unregister(process)+++def _frame(key: tuple, size: tuple[int, int] | None, controller=None) -> _CachedFrame:+ global _cached_frame+ with _lock:+ if _cached_frame is not None and _cached_frame.key == key:+ return _cached_frame+ path = Path(key[0])+ rgba = decode_image(path).rgba if key[3] == "Image" else _video_frame(path, key[4], size, controller)+ if rgba.shape[0] * rgba.shape[1] > MAX_PREVIEW_PIXELS:+ raise FastPreviewUnavailable("This image is too large for the in-memory preview.")+ frame = _CachedFrame(key, rgba)+ if rgba.nbytes <= _MAX_CACHE_BYTES:+ with _lock:+ _cached_frame = frame+ return frame+++def render_color_still_preview(source: str | Path, settings: UISettings, mode: str,+ *, start_seconds: float = 0.0,+ video_size: tuple[int, int] | None = None,+ controller=None, progress=None) -> tuple[np.ndarray, str]:+ """Grade a source-resolution frame on Vulkan with the same cube as export."""+ if mode not in {"Image", "Video"}:+ raise ValueError("Unsupported coloring preview mode.")+ if mode == "Video" and video_size is None:+ raise ValueError("Video dimensions are required for the fast preview.")+ key = _source_key(source, mode, start_seconds, video_size)+ if controller is not None and controller.cancel.is_set():+ raise Cancelled("Preview superseded by newer settings.")+ frame = _frame(key, video_size, controller)+ if progress is not None:+ progress(0.35, "Coloring: source frame ready")+ if controller is not None and controller.cancel.is_set():+ raise Cancelled("Preview superseded by newer settings.")+ prepared = _prepared_lut(settings, controller)+ result = apply_cube_lut_file(frame.rgba, prepared.path, controller=controller, selection=settings.ffmpeg_device)+ if controller is not None and controller.cancel.is_set():+ raise Cancelled("Preview superseded by newer settings.")+ if progress is not None:+ progress(1.0, "Coloring preview complete")+ return result, ""diff --git a/src/desktop/coloring.py b/src/desktop/coloring.pyindex c1c4273..3575d3e 100644--- a/src/desktop/coloring.py+++ b/src/desktop/coloring.py@@ -206,12 +206,15 @@ def _graded_cube_slices(source: CubeLUT, settings: UISettings, size: int):yield grade_lut_rgb(identity, sampled, settings).reshape(size, size, 3)-def compose_cube_lut(source: CubeLUT, settings: UISettings, size: int) -> CubeLUT:+def compose_cube_lut(source: CubeLUT, settings: UISettings, size: int, *, controller=None) -> CubeLUT:"""Bake the selected LUT and grading controls into a standard RGB cube."""if size not in (33, 65, 129):raise ValueError("LUT resolution must be 33, 65, or 129.")values = np.empty((size, size, size, 3), dtype=np.float32)for index, plane in enumerate(_graded_cube_slices(source, settings, size)):+ if controller is not None and controller.cancel.is_set():+ from ..core.jobs import Cancelled+ raise Cancelled("LUT preview cancelled.")values[index] = planereturn CubeLUT(size, np.zeros(3, dtype=np.float32),np.ones(3, dtype=np.float32), values)@@ -248,20 +251,39 @@ def save_cube_lut(destination: str | Path, source_path: str | Path | None,return target-def apply_cube_lut(rgba: np.ndarray, lut: CubeLUT) -> np.ndarray:- """Apply trilinear RGB interpolation in chunks, preserving source alpha and depth."""- result = np.empty_like(rgba)+def write_composed_lut(path: str | Path, lut: CubeLUT, *, controller=None) -> None:+ """Serialize an already composed cube without changing its precision."""+ with Path(path).open("w", encoding="ascii") as stream:+ stream.write(f"LUT_3D_SIZE {lut.size}\n")+ stream.write("DOMAIN_MIN " + " ".join(map(str, lut.domain_min)) + "\n")+ stream.write("DOMAIN_MAX " + " ".join(map(str, lut.domain_max)) + "\n")+ for plane in lut.values:+ if controller is not None and controller.cancel.is_set():+ from ..core.jobs import Cancelled+ raise Cancelled("LUT preview cancelled.")+ np.savetxt(stream, plane.reshape(-1, 3), fmt="%.9f")+++def apply_cube_lut_file(rgba: np.ndarray, path: str | Path, *, controller=None, selection=None) -> np.ndarray:+ """Apply a prepared cube on Vulkan, preserving alpha and sample depth."""+ from ..core.ffmpeg.filters import filter_array+ from ..core.ffmpeg.vulkan import libplacebo, quote_filter_path+ opaque = rgba.copy()+ opaque[..., 3] = np.iinfo(rgba.dtype).max+ result = filter_array(opaque, libplacebo("lut=" + quote_filter_path(path) + ":lut_type=native"),+ controller=controller, selection=selection)result[..., 3] = rgba[..., 3]- maximum = float(np.iinfo(rgba.dtype).max)- rows_per_chunk = max(1, 262_144 // max(1, rgba.shape[1]))- for top in range(0, rgba.shape[0], rows_per_chunk):- bottom = min(rgba.shape[0], top + rows_per_chunk)- rgb = rgba[top:bottom, :, :3].astype(np.float32) / maximum- color = sample_cube_lut(rgb, lut)- result[top:bottom, :, :3] = np.rint(np.clip(color, 0.0, 1.0) * maximum).astype(rgba.dtype)return result+def apply_cube_lut(rgba: np.ndarray, lut: CubeLUT, *, controller=None, selection=None) -> np.ndarray:+ """Apply a cube on Vulkan, preserving source alpha and sample depth."""+ with tempfile.TemporaryDirectory(prefix="visual-enhancer-lut-") as directory:+ path = Path(directory) / "filter.cube"+ write_composed_lut(path, lut, controller=controller)+ return apply_cube_lut_file(rgba, path, controller=controller, selection=selection)++def _lab_statistics(rgba: np.ndarray) -> tuple[np.ndarray, np.ndarray] | None:"""Measure visible pixels on a bounded preview, regardless of image size."""height, width = rgba.shape[:2]diff --git a/src/desktop/denoising.py b/src/desktop/denoising.pydeleted file mode 100644index b2a9aa1..0000000--- a/src/desktop/denoising.py+++ /dev/null@@ -1,155 +0,0 @@-"""Quality-first, lossless intermediate denoising for ordered image/video stages."""--from __future__ import annotations--from pathlib import Path-from typing import Callable--import cv2-import numpy as np-import tifffile--from ..core import ffmpeg-from ..core.jobs import Cancelled, JobController-from ..core.paths import FFMPEG-from ..neural_rendering.image.decoder import decode_image-from ..neural_rendering.image.encoder import _encode_image-from ..neural_rendering.image.models import ImageConversionOptions-from ..settings.models import UISettings---def _filters(settings: UISettings, *, video: bool, small: bool = False) -> str:- """Run deblocking before NLM, so patch matching sees fewer 8×8 seams."""- filters = ["format=gbrp10le" if video else "format=gbrp16le"]- if settings.denoise_deblock and not small:- # Weak edge-aware deblocking avoids flattening legitimate drawn lines.- filters.append("deblock=filter=weak:block=8:alpha=0.05:beta=0.03:gamma=0.03:delta=0.03")- if settings.denoise_strength:- level = settings.denoise_strength- strength = 1.0 + 0.01 * level + 0.0014 * level * level- patch = 3 if small else 7- search = 7 if small else 21- filters.append(f"nlmeans=s={strength:.2f}:p={patch}:r={search}")- if video and settings.denoise_temporal:- # Adaptive temporal averaging rejects sufficiently different neighbours- # at moving edges and scene changes. Keep the default threshold gentle.- threshold_a = 0.006 + 0.00026 * settings.denoise_temporal- threshold_b = threshold_a * 2.0- window = 9 if settings.denoise_temporal > 65 else 5- thresholds = ":".join(- f"{plane}{suffix}={value:.5f}"- for plane in range(3)- for suffix, value in (("a", threshold_a), ("b", threshold_b))- )- filters.append(f"atadenoise=s={window}:{thresholds}")- filters.append("format=gbrp10le" if video else "format=rgb48le")- return ",".join(filters)---def denoise_image(source: Path, settings: UISettings, directory: Path,- controller: JobController, progress: Callable,- run_command: Callable) -> Path:- if not settings.denoise_strength and not settings.denoise_deblock:- progress(1.0, "Denoising complete")- return source- if controller.cancel.is_set():- raise Cancelled("Render stopped by user.")- decoded = decode_image(source)- height, width = decoded.rgba.shape[:2]- output = directory / "denoised.tiff"- small = min(width, height) < 16- original_rgb = np.ascontiguousarray(decoded.rgba[..., :3])- progress(0.15, "Cleaning image noise")- if decoded.rgba.dtype == np.uint8:- # OpenCV's Lab-space colored NLM keeps fine luma detail better than a- # single RGB strength. Equal luma/chroma settings avoid color smearing.- filtered_rgb = original_rgb- if settings.denoise_deblock and not small:- filtered_rgb = _ffmpeg_image_filter(- filtered_rgb, directory, controller, run_command,- "format=gbrp16le,deblock=filter=weak:block=8:alpha=0.05:beta=0.03:gamma=0.03:delta=0.03,format=rgb48le",- )- if settings.denoise_strength:- level = settings.denoise_strength- luma = 1.0 + 0.024 * level + 0.0008 * level * level- chroma = luma- bgr = cv2.cvtColor(filtered_rgb, cv2.COLOR_RGB2BGR)- cleaned = cv2.fastNlMeansDenoisingColored(- bgr, None, luma, chroma, 3 if small else 7, 7 if small else 21,- )- filtered_rgb = cv2.cvtColor(cleaned, cv2.COLOR_BGR2RGB)- else:- # The colored OpenCV variant is 8-bit only. FFmpeg's 16-bit NLM avoids- # reducing genuine high-depth image samples to 8-bit for this stage.- filtered_rgb = _ffmpeg_image_filter(- original_rgb, directory, controller, run_command,- _filters(settings, video=False, small=small),- )- rgba = decoded.rgba.copy()- rgba[..., :3] = filtered_rgb- if decoded.alpha is not None:- # Retain colors on nonopaque pixels so denoising cannot pull invisible- # background colors across a transparency boundary.- rgba[decoded.alpha < np.iinfo(rgba.dtype).max, :3] = decoded.rgba[- decoded.alpha < np.iinfo(rgba.dtype).max, :3]- if controller.cancel.is_set():- raise Cancelled("Render stopped by user.")- progress(0.85, "Saving denoised image")- _encode_image(output, rgba,- ImageConversionOptions(output_format="TIFF", preserve_metadata=False),- {}, generate_preview=False, controller=controller,- has_transparency=decoded.alpha is not None)- progress(1.0, "Denoising complete")- return output---def _ffmpeg_image_filter(rgb: np.ndarray, directory: Path,- controller: JobController, run_command: Callable,- filter_graph: str) -> np.ndarray:- height, width = rgb.shape[:2]- input_path = directory / "denoise-input.tiff"- filtered_path = directory / "denoise-filtered.tiff"- tifffile.imwrite(input_path, rgb, photometric="rgb", compression=None, metadata=None)- run_command(- [str(FFMPEG), "-hide_banner", "-loglevel", "error", "-y",- "-i", str(input_path), "-vf", filter_graph,- "-frames:v", "1", str(filtered_path)],- controller, "Image denoising",- )- filtered_bgr = cv2.imread(str(filtered_path), cv2.IMREAD_UNCHANGED)- if (filtered_bgr is None or filtered_bgr.dtype != np.uint16- or filtered_bgr.shape != (height, width, 3)):- raise RuntimeError("Image denoising returned invalid 16-bit RGB pixels.")- filtered_rgb = cv2.cvtColor(filtered_bgr, cv2.COLOR_BGR2RGB)- if rgb.dtype == np.uint8:- return ((filtered_rgb.astype(np.uint32) + 128) // 257).astype(np.uint8)- return filtered_rgb---def denoise_video(source: Path, settings: UISettings, directory: Path,- controller: JobController, progress: Callable,- run_command: Callable) -> Path:- if not (settings.denoise_strength or settings.denoise_deblock or settings.denoise_temporal):- progress(1.0, "Denoising complete")- return source- metadata = ffmpeg.probe_video(source, count_mode="metadata", controller=controller)- width, height = int(metadata["width"]), int(metadata["height"])- color_args: list[str] = []- for key, flag in (("color_primaries", "-color_primaries"),- ("color_transfer", "-color_trc")):- value = metadata.get(key)- if value and value != "unknown":- color_args.extend((flag, str(value)))- output = directory / "denoised.mkv"- progress(0.1, "Cleaning video noise")- run_command(- [str(FFMPEG), "-hide_banner", "-loglevel", "error", "-y",- "-i", str(source), "-map", "0:v:0", "-map_metadata", "0", "-an",- "-vf", _filters(settings, video=True, small=min(width, height) < 16),- "-c:v", "ffv1", "-level", "3", "-pix_fmt", "gbrp10le",- "-fps_mode", "passthrough", *color_args, "-color_range", "pc",- str(output)],- controller, "Video denoising",- )- progress(1.0, "Denoising complete")- return outputdiff --git a/src/desktop/i18n.py b/src/desktop/i18n.pynew file mode 100644index 0000000..d6f09d5--- /dev/null+++ b/src/desktop/i18n.py@@ -0,0 +1,119 @@+"""Qt6 translations and desktop language preferences.++Catalogs use one explicit App context so QML and Python share terminology.+The language is a desktop preference, independent of processing presets.+"""+from __future__ import annotations++from pathlib import Path+import re++from PySide6.QtCore import QCoreApplication, QLibraryInfo, QLocale, QTranslator+from PySide6.QtGui import QFontDatabase, QGuiApplication+++DEFAULT_LANGUAGE = "en_US"+LANGUAGES = (+ ("en_US", "English (US)", "Segoe UI"),+ ("ar", "العربية", "Segoe UI"),+ ("de", "Deutsch", "Segoe UI"),+ ("es", "Español", "Segoe UI"),+ ("fr", "Français", "Segoe UI"),+ ("hi", "हिन्दी", "Nirmala UI"),+ ("ja", "日本語", "Yu Gothic UI"),+ ("ko", "한국어", "Malgun Gothic"),+ ("pl", "Polski", "Segoe UI"),+ ("uk", "Українська", "Segoe UI"),+ ("zh_CN", "中文 (简体)", "Microsoft YaHei UI"),+ ("zh_TW", "中文 (繁體)", "Microsoft JhengHei UI"),+)+LANGUAGE_CODES = frozenset(code for code, _, _ in LANGUAGES)+CATALOG_DIR = Path(__file__).resolve().parent / "translations"+++def tr(source: str) -> str:+ return QCoreApplication.translate("App", source)+++class UiMessage(str):+ """Retain the English diagnostic plus arguments for live retranslation."""++ def __new__(cls, source: str, *args):+ values = tuple(str(arg) for arg in args)+ obj = super().__new__(cls, _substitute(source, values))+ obj.source = source+ obj.args = args+ return obj+++def _substitute(source: str, args: tuple[str, ...]) -> str:+ return re.sub(r"%([1-9]\d*)", lambda match: args[int(match[1]) - 1], source)+++def translate_text(value: str) -> str:+ if isinstance(value, UiMessage):+ return _substitute(tr(value.source), tuple(translate_text(arg) if isinstance(arg, UiMessage) else str(arg) for arg in value.args))+ return tr(value)+++def join_messages(values: list[str], separator: str = "\n") -> UiMessage:+ return UiMessage(separator.join(f"%{index+1}" for index in range(len(values))), *values)+++def language_choices() -> list[dict[str, str]]:+ available = set(QFontDatabase.families())+ fallback = QGuiApplication.font().family()+ return [{"value": code, "label": name, "fontFamily": font if font in available else fallback}+ for code, name, font in LANGUAGES]+++class LanguageManager:+ """Keep translators alive and replace them before QML retranslation."""++ def __init__(self, language: str = DEFAULT_LANGUAGE):+ self.language = DEFAULT_LANGUAGE+ self._translators: list[QTranslator] = []+ self.set_language(language if language in LANGUAGE_CODES else DEFAULT_LANGUAGE)++ def close(self) -> None:+ app = QGuiApplication.instance()+ for translator in self._translators:+ if app is not None:+ app.removeTranslator(translator)+ translator.deleteLater()+ self._translators.clear()++ def set_language(self, language: str) -> bool:+ if language not in LANGUAGE_CODES:+ return False+ app = QGuiApplication.instance()+ if app is None:+ raise RuntimeError("Create QGuiApplication before installing translations.")+ translators = []+ locale = QLocale(language)+ if language != DEFAULT_LANGUAGE:+ # Stock Qt strings (dialog buttons, file pickers, context menus).+ qt_dir = QLibraryInfo.path(QLibraryInfo.LibraryPath.TranslationsPath)+ for catalog in ("qtbase", "qtdeclarative"):+ translator = QTranslator(app)+ if translator.load(locale, catalog, "_", qt_dir):+ translators.append(translator)+ translator = QTranslator(app)+ if not translator.load(str(CATALOG_DIR / f"app_{language}.qm")):+ raise RuntimeError(f"Missing language catalog: {language}")+ translators.append(translator)+ self.close()+ for translator in translators:+ app.installTranslator(translator)+ self._translators = translators+ self.language = language+ QLocale.setDefault(locale)+ app.setLayoutDirection(locale.textDirection())+ # Qt performs glyph fallback/shaping; the selected base font also+ # supplies appropriate metrics for Hindi, Japanese, Korean and Chinese.+ preferred = next(font for code, _, font in LANGUAGES if code == language)+ font = app.font()+ if preferred in QFontDatabase.families():+ font.setFamily(preferred)+ app.setFont(font)+ return Truediff --git a/src/desktop/models.py b/src/desktop/models.pyindex 4466d19..eb4c23a 100644--- a/src/desktop/models.py+++ b/src/desktop/models.py@@ -1,6 +1,8 @@from __future__ import annotationsfrom dataclasses import dataclass+import math+import refrom pathlib import Pathfrom typing import Any@@ -20,11 +22,25 @@ class BatchEntry:output_dimensions: str = ""thumbnail_url: str = ""selected: bool = False+ file_size_bytes: int = 0+ duration_seconds: float = 0.0+ frame_count: int = 0+ processed_frames: int = 0+ processing_total_frames: int = 0+ processing_fps: float = 0.0+ _frame_sample: tuple[str, int, float] | None = None@propertydef file_name(self) -> str:return Path(self.input_path).name+ @property+ def remaining_seconds(self) -> float:+ """Estimate the entire file job from job progress, never stage frame counters."""+ if self.state != "Running" or self.elapsed_seconds < 1 or self.progress <= 0.01:+ return -1.0+ return self.elapsed_seconds * (1 - self.progress) / self.progress+class BatchListModel(QAbstractListModel):"""QML list model used by all desktop batch queues."""@@ -44,6 +60,15 @@ class BatchListModel(QAbstractListModel):ThumbnailUrlRole = Qt.ItemDataRole.UserRole + 10IndexRole = Qt.ItemDataRole.UserRole + 11SelectedRole = Qt.ItemDataRole.UserRole + 12+ FileSizeBytesRole = Qt.ItemDataRole.UserRole + 13+ DurationSecondsRole = Qt.ItemDataRole.UserRole + 14+ FrameCountRole = Qt.ItemDataRole.UserRole + 15+ ProcessedFramesRole = Qt.ItemDataRole.UserRole + 16+ ProcessingTotalFramesRole = Qt.ItemDataRole.UserRole + 17+ ProcessingFpsRole = Qt.ItemDataRole.UserRole + 18+ RemainingSecondsRole = Qt.ItemDataRole.UserRole + 19++ _frame_counter = re.compile(r"([\d,]+)\s*/\s*([\d,]+)\s+frames\b", re.IGNORECASE)def __init__(self, parent: Any = None) -> None:super().__init__(parent)@@ -78,6 +103,13 @@ class BatchListModel(QAbstractListModel):self.ThumbnailUrlRole: entry.thumbnail_url,self.IndexRole: entry.index,self.SelectedRole: entry.selected,+ self.FileSizeBytesRole: float(entry.file_size_bytes),+ self.DurationSecondsRole: entry.duration_seconds,+ self.FrameCountRole: entry.frame_count,+ self.ProcessedFramesRole: entry.processed_frames,+ self.ProcessingTotalFramesRole: entry.processing_total_frames,+ self.ProcessingFpsRole: entry.processing_fps,+ self.RemainingSecondsRole: entry.remaining_seconds,}return mapping.get(role)@@ -86,7 +118,7 @@ class BatchListModel(QAbstractListModel):self.FileNameRole: QByteArray(b"fileName"),self.InputPathRole: QByteArray(b"inputPath"),self.OutputPathRole: QByteArray(b"outputPath"),- self.StateRole: QByteArray(b"state"),+ self.StateRole: QByteArray(b"itemState"),self.ProgressRole: QByteArray(b"progress"),self.DetailRole: QByteArray(b"detail"),self.ElapsedSecondsRole: QByteArray(b"elapsedSeconds"),@@ -95,12 +127,28 @@ class BatchListModel(QAbstractListModel):self.ThumbnailUrlRole: QByteArray(b"thumbnailUrl"),self.IndexRole: QByteArray(b"itemIndex"),self.SelectedRole: QByteArray(b"selected"),+ self.FileSizeBytesRole: QByteArray(b"fileSizeBytes"),+ self.DurationSecondsRole: QByteArray(b"durationSeconds"),+ self.FrameCountRole: QByteArray(b"frameCount"),+ self.ProcessedFramesRole: QByteArray(b"processedFrames"),+ self.ProcessingTotalFramesRole: QByteArray(b"processingTotalFrames"),+ self.ProcessingFpsRole: QByteArray(b"processingFps"),+ self.RemainingSecondsRole: QByteArray(b"remainingSeconds"),}+ @staticmethod+ def _new_entry(index: int, path: str) -> BatchEntry:+ try:+ size = Path(path).stat().st_size+ except OSError:+ size = 0+ return BatchEntry(index=index, input_path=path, file_size_bytes=size)+@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()]+ valid_paths = [p for p in paths if p and Path(p).is_file()]+ self._entries = [self._new_entry(i, p) for i, p in enumerate(valid_paths)]self._selected_index = 0 if self._entries else -1if self._selected_index >= 0:self._entries[0].selected = True@@ -124,7 +172,7 @@ class BatchListModel(QAbstractListModel):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._entries.append(self._new_entry(start + i, path))self.endInsertRows()self.countChanged.emit()if self._selected_index < 0:@@ -156,6 +204,8 @@ class BatchListModel(QAbstractListModel):for i, e in enumerate(self._entries):e.index = iself.endRemoveRows()+ if row < len(self._entries):+ self.dataChanged.emit(self.index(row), self.index(len(self._entries) - 1), [self.IndexRole])if not self._entries:new_selected = -1elif self._selected_index == row:@@ -194,7 +244,8 @@ class BatchListModel(QAbstractListModel):return Nonedef update_metadata(self, row: int, *, input_dimensions: str | None = None,- output_dimensions: str | None = None, thumbnail_url: str | None = None) -> None:+ output_dimensions: str | None = None, thumbnail_url: str | None = None,+ duration_seconds: float | None = None, frame_count: int | None = None) -> None:if not (0 <= row < len(self._entries)):returnentry = self._entries[row]@@ -208,6 +259,12 @@ class BatchListModel(QAbstractListModel):if thumbnail_url is not None:entry.thumbnail_url = thumbnail_urlroles.append(self.ThumbnailUrlRole)+ if duration_seconds is not None:+ entry.duration_seconds = max(0.0, float(duration_seconds))+ roles.append(self.DurationSecondsRole)+ if frame_count is not None:+ entry.frame_count = max(0, int(frame_count))+ roles.append(self.FrameCountRole)if roles:idx = self.index(row)self.dataChanged.emit(idx, idx, roles)@@ -220,16 +277,42 @@ class BatchListModel(QAbstractListModel):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+ # Backend fractions cover the whole file, including export. Stage changes+ # must never rewind the bar, and only a published result can reach 100%.+ if state in {"Completed", "CompletedWithWarnings"}:+ entry.progress = 1.0+ elif state == "Queued":+ entry.progress = 0.0+ elif math.isfinite(progress):+ limit = 0.99 if state == "Running" else 1.0+ entry.progress = max(entry.progress, max(0.0, min(limit, float(progress))))+ entry.detail = detailif output_path:entry.output_path = output_path- if elapsed_seconds >= 0:- entry.elapsed_seconds = elapsed_seconds+ if math.isfinite(elapsed_seconds) and elapsed_seconds >= 0:+ entry.elapsed_seconds = max(entry.elapsed_seconds, elapsed_seconds)+ counter = self._frame_counter.search(detail) if state == "Running" else None+ if counter:+ current, total = (int(value.replace(",", "")) for value in counter.groups())+ stage = detail[:counter.start()].rstrip(" :·–-")+ sample = entry._frame_sample+ if sample and sample[0] == stage and current >= sample[1] and elapsed_seconds > sample[2]:+ measured = (current - sample[1]) / (elapsed_seconds - sample[2])+ entry.processing_fps = measured if entry.processing_fps <= 0 else (+ 0.35 * measured + 0.65 * entry.processing_fps)+ else:+ entry.processing_fps = 0.0+ entry._frame_sample = (stage, current, elapsed_seconds)+ entry.processed_frames, entry.processing_total_frames = current, total+ else:+ entry._frame_sample = None+ entry.processing_fps = 0.0+ entry.processed_frames = 0+ entry.processing_total_frames = 0idx = self.index(index)self.dataChanged.emit(idx, idx, [self.StateRole, self.ProgressRole, self.DetailRole,- self.OutputPathRole, self.ElapsedSecondsRole])+ self.OutputPathRole, self.ElapsedSecondsRole, self.ProcessedFramesRole,+ self.ProcessingTotalFramesRole, self.ProcessingFpsRole, self.RemainingSecondsRole])@Slot()@@ -237,8 +320,9 @@ class BatchListModel(QAbstractListModel):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)+ # Remove rows in place so retained files keep their metadata and progress.+ for row in reversed(remove):+ self.remove_item(row)@Slot()def retry_failed(self) -> None:@@ -250,8 +334,13 @@ class BatchListModel(QAbstractListModel):entry.detail = ""entry.output_path = ""entry.elapsed_seconds = 0.0+ entry.processed_frames = entry.processing_total_frames = 0+ entry.processing_fps = 0.0+ entry._frame_sample = Noneidx = self.index(row)- self.dataChanged.emit(idx, idx, [self.StateRole, self.ProgressRole, self.DetailRole, self.OutputPathRole, self.ElapsedSecondsRole])+ self.dataChanged.emit(idx, idx, [self.StateRole, self.ProgressRole, self.DetailRole,+ self.OutputPathRole, self.ElapsedSecondsRole, self.ProcessedFramesRole,+ self.ProcessingTotalFramesRole, self.ProcessingFpsRole, self.RemainingSecondsRole])changed = Trueif changed and self._selected_index < 0 and self._entries:self.select(0)@@ -265,6 +354,10 @@ class BatchListModel(QAbstractListModel):e.detail = ""e.output_path = ""e.elapsed_seconds = 0.0+ e.processed_frames = e.processing_total_frames = 0+ e.processing_fps = 0.0+ e._frame_sample = Noneself.dataChanged.emit(self.index(0), self.index(len(self._entries) - 1),[self.StateRole, self.ProgressRole, self.DetailRole,- self.OutputPathRole, self.ElapsedSecondsRole])+ self.OutputPathRole, self.ElapsedSecondsRole, self.ProcessedFramesRole,+ self.ProcessingTotalFramesRole, self.ProcessingFpsRole, self.RemainingSecondsRole])diff --git a/src/desktop/nis_sharpening.py b/src/desktop/nis_sharpening.pydeleted file mode 100644index 5930b20..0000000--- a/src/desktop/nis_sharpening.py+++ /dev/null@@ -1,151 +0,0 @@-"""NVIDIA Image Scaling SDK 1.0.3 NVSharpen-only math for RGB media.--This is a vectorized CPU port of the ``NIS_SCALER=0`` path in-``native (dev)/NVIDIAImageScaling/NIS/NIS_Scaler.h``. It uses the SDK's-``NVSharpenUpdateConfig`` parameters, four directional USM filters,-edge detection and anti-ringing limiter. No NIS scaling code is used.-"""--# NVSharpen algorithm adapted from NVIDIA Image Scaling SDK 1.0.3.-# Copyright (c) 2022 NVIDIA CORPORATION & AFFILIATES.-# See NVIDIA-NIS-LICENSE.txt in this directory.--from __future__ import annotations--import numpy as np--from ..core.jobs import Cancelled, JobController---def _configuration(sharpness: int) -> tuple[float, float, float, float, float, float]:- """The SDR constants from NVScalerUpdateConfig / NVSharpenUpdateConfig."""- slider = sharpness / 100.0 - 0.5- max_scale = 1.25 if slider >= 0.0 else 1.75- min_scale = 1.25 if slider >= 0.0 else 1.0- limit_scale = 1.25 if slider >= 0.0 else 1.0- strength_min = max(0.0, 0.4 + slider * min_scale * 1.2)- strength_max = 1.6 + slider * max_scale * 1.8- limit_min = max(0.1, 0.14 + slider * limit_scale * 0.32)- limit_max = 0.5 + slider * limit_scale * 0.6- return (0.45, 1.0 / (0.9 - 0.45), strength_min,- strength_max - strength_min, limit_min, limit_max - limit_min)---def _lti(samples: tuple[np.ndarray, ...]) -> np.ndarray:- a, b, c, d, e = samples- a_min = np.minimum(np.minimum(a, b), c)- a_max = np.maximum(np.maximum(a, b), c)- b_min = np.minimum(np.minimum(c, d), e)- b_max = np.maximum(np.maximum(c, d), e)- a_contrast = a_max - a_min- b_contrast = b_max - b_min- ratio = np.maximum(a_contrast, b_contrast) / (- np.minimum(a_contrast, b_contrast) + np.float32(1.0 / 255.0))- return 1.0 - np.clip((ratio - 2.0) / 8.0, 0.0, 1.0)---def _directional_usm(samples: tuple[np.ndarray, ...], strength: np.ndarray,- limit: np.ndarray) -> np.ndarray:- usm = (-0.6001 * samples[1] + 1.2002 * samples[2]- - 0.6001 * samples[3])- usm = np.clip(usm * strength, -limit, limit)- return usm * _lti(samples)---def _edge_weights(p: list[list[np.ndarray]]) -> tuple[np.ndarray, ...]:- """GetEdgeMap(p, 1, 1) from the SDK's NVSharpen path."""- g0 = np.abs(p[1][1] + p[1][2] + p[1][3]- - p[3][1] - p[3][2] - p[3][3])- g45 = np.abs(p[2][1] + p[1][1] + p[1][2]- - p[3][2] - p[3][3] - p[2][3])- g90 = np.abs(p[1][1] + p[2][1] + p[3][1]- - p[1][3] - p[2][3] - p[3][3])- g135 = np.abs(p[2][1] + p[3][1] + p[3][2]- - p[1][2] - p[1][3] - p[2][3])-- axis_max = np.maximum(g0, g90)- axis_min = np.minimum(g0, g90)- diagonal_max = np.maximum(g45, g135)- diagonal_min = np.minimum(g45, g135)- total = axis_max + diagonal_max- axis_fraction = np.divide(axis_max, total, out=np.zeros_like(total),- where=total > 0)- diagonal_fraction = 1.0 - axis_fraction- detect_ratio = 2.0 * 1127.0 / 1024.0- threshold = 64.0 / 1024.0- axis_detected = ((axis_max > axis_min * detect_ratio) &- (axis_max > threshold) & (axis_max > diagonal_min))- diagonal_detected = ((diagonal_max > diagonal_min * detect_ratio) &- (diagonal_max > threshold) & (diagonal_max > axis_min))- both = axis_detected & diagonal_detected- axis_factor = np.where(both, axis_fraction, 1.0)- diagonal_factor = np.where(both, diagonal_fraction, 1.0)- return (np.where(axis_detected & (g0 >= g90), axis_factor, 0.0),- np.where(axis_detected & (g0 < g90), axis_factor, 0.0),- np.where(diagonal_detected & (g45 >= g135), diagonal_factor, 0.0),- np.where(diagonal_detected & (g45 < g135), diagonal_factor, 0.0))---def sharpen_rgb(pixels: np.ndarray, sharpness: int, *,- alpha: np.ndarray | None = None,- controller: JobController | None = None) -> np.ndarray:- """Apply SDK NVSharpen without resizing 8/16-bit display-referred RGB."""- if pixels.ndim != 3 or pixels.shape[2] != 3 or pixels.dtype not in (np.uint8, np.uint16):- raise ValueError("NIS requires an 8-bit or 16-bit RGB image.")- if isinstance(sharpness, bool) or not isinstance(sharpness, int) or not 0 <= sharpness <= 100:- raise ValueError("NIS sharpness must be an integer from 0 to 100.")- if alpha is not None and (alpha.shape != pixels.shape[:2] or alpha.dtype != pixels.dtype):- raise ValueError("NIS alpha must match the RGB pixels.")- if sharpness == 0 or min(pixels.shape[:2]) < 2:- return pixels.copy()-- height, width = pixels.shape[:2]- maximum = float(np.iinfo(pixels.dtype).max)- start_y, scale_y, strength_min, strength_scale, limit_min, limit_scale = _configuration(sharpness)- result = np.empty_like(pixels)- tile = 256- for y in range(0, height, tile):- for x in range(0, width, tile):- if controller is not None and controller.cancel.is_set():- raise Cancelled("Render stopped by user.")- bottom, right = min(height, y + tile), min(width, x + tile)- tile_height, tile_width = bottom - y, right - x- y0, y1 = max(0, y - 2), min(height, bottom + 2)- x0, x1 = max(0, x - 2), min(width, right + 2)- border = ((max(0, 2 - y), max(0, bottom + 2 - height)),- (max(0, 2 - x), max(0, right + 2 - width)))- block = np.pad(pixels[y0:y1, x0:x1], (*border, (0, 0)), mode="edge")- block = block.astype(np.float32) / maximum- luma = (np.float32(0.2126) * block[..., 0]- + np.float32(0.7152) * block[..., 1]- + np.float32(0.0722) * block[..., 2])- p = [[luma[i:i + tile_height, j:j + tile_width]- for j in range(5)] for i in range(5)]-- scale = 1.0 - np.clip((p[2][2] - start_y) * scale_y, 0.0, 1.0)- strength = scale * strength_scale + strength_min- limit = (scale * limit_scale + limit_min) * p[2][2]- directions = (- (p[0][2], p[1][2], p[2][2], p[3][2], p[4][2]),- (p[2][0], p[2][1], p[2][2], p[2][3], p[2][4]),- (p[1][1], 0.5 * (p[2][1] + p[1][2]), p[2][2],- 0.5 * (p[3][2] + p[2][3]), p[3][3]),- (p[3][1], 0.5 * (p[3][2] + p[2][1]), p[2][2],- 0.5 * (p[2][3] + p[1][2]), p[1][3]),- )- weights = _edge_weights(p)- usm = np.zeros_like(p[2][2])- for samples, weight in zip(directions, weights):- usm += _directional_usm(samples, strength, limit) * weight-- center = block[2:-2, 2:-2]- if alpha is not None:- a = np.pad(alpha[y0:y1, x0:x1], border, mode="edge")- opaque = np.ones((tile_height, tile_width), dtype=bool)- for dy in range(5):- for dx in range(5):- opaque &= a[dy:dy + tile_height, dx:dx + tile_width] == maximum- usm = np.where(opaque, usm, 0.0)- sharpened = np.clip(center + usm[..., None], 0.0, 1.0)- result[y:bottom, x:right] = np.rint(sharpened * maximum).astype(pixels.dtype)- return resultdiff --git a/src/desktop/preview_cache.py b/src/desktop/preview_cache.pyindex 4692329..6f76f63 100644--- a/src/desktop/preview_cache.py+++ b/src/desktop/preview_cache.py@@ -20,7 +20,7 @@ from typing import Anyfrom ..core.paths import PREVIEW_CACHE-CACHE_SCHEMA = 1+CACHE_SCHEMA = 2_LOCK = threading.RLock()diff --git a/src/desktop/preview_player.py b/src/desktop/preview_player.pynew file mode 100644index 0000000..d22091d--- /dev/null+++ b/src/desktop/preview_player.py@@ -0,0 +1,377 @@+"""Decode cached video straight into Qt's display surface, without a video encode.++Qt's bundled decoder converts planar RGB10 to RGB8 and loses HDR signaling.+Use the application's decoder instead and upload 10-bit display frames. RGB10+cache files stay untouched; the YUV conversion exists only in display memory.+"""+from __future__ import annotations++from collections import deque+import math+import subprocess+import threading+import time++import av+import numpy as np+from PySide6.QtCore import QObject, Property, QRect, QSize, QTimer, QUrl, Signal, Slot+from PySide6.QtMultimedia import QVideoFrame, QVideoFrameFormat++from ..core.ffmpeg.probe import probe_video+from ..core.jobs import BoundedLogBuffer, JobController, drain_bounded_text+from ..core.paths import FFMPEG+++class _PipeReader:+ def __init__(self, pipe):+ self.pipe = pipe++ def read(self, size):+ return self.pipe.read(size)+++def _display_format(metadata: dict) -> QVideoFrameFormat:+ width, height = int(metadata["width"]), int(metadata["height"])+ result = QVideoFrameFormat(QSize((width + 1) // 2 * 2, (height + 1) // 2 * 2),+ QVideoFrameFormat.PixelFormat.Format_P010)+ result.setViewport(QRect(0, 0, width, height))+ result.setColorRange(QVideoFrameFormat.ColorRange.ColorRange_Video)+ space = QVideoFrameFormat.ColorSpace+ result.setColorSpace(space.ColorSpace_BT2020 if metadata.get("color_primaries") == "bt2020"+ else space.ColorSpace_BT709)+ transfer = QVideoFrameFormat.ColorTransfer+ result.setColorTransfer({+ "smpte2084": transfer.ColorTransfer_ST2084,+ "arib-std-b67": transfer.ColorTransfer_STD_B67,+ "linear": transfer.ColorTransfer_Linear,+ "gamma22": transfer.ColorTransfer_Gamma22,+ "gamma28": transfer.ColorTransfer_Gamma28,+ }.get(metadata.get("color_transfer"), transfer.ColorTransfer_BT709))+ return result+++def _display_frame(pixels: bytes, display_format: QVideoFrameFormat,+ position_us: int, duration_us: int) -> QVideoFrame:+ width, height = display_format.frameWidth(), display_format.frameHeight()+ if len(pixels) != width * height * 3:+ raise RuntimeError("Preview decoder returned an incomplete display frame.")+ result = QVideoFrame(display_format)+ if not result.map(QVideoFrame.MapMode.WriteOnly):+ raise RuntimeError("Cannot allocate the preview display frame.")+ try:+ offset = 0+ for index, rows in enumerate((height, height // 2)):+ # P010: a 16-bit luma plane followed by interleaved 16-bit U/V.+ row_bytes = width * 2+ size = rows * row_bytes+ source = np.frombuffer(pixels, dtype=np.uint8, count=size, offset=offset).reshape(rows, row_bytes)+ target = np.frombuffer(result.bits(index), dtype=np.uint8).reshape(+ rows, result.bytesPerLine(index))+ target[:, :row_bytes] = source[:, :row_bytes]+ offset += size+ finally:+ result.unmap()+ result.setStartTime(position_us)+ result.setEndTime(position_us + duration_us)+ return result+++class PreviewPlayer(QObject):+ """Silent, bounded preview player; the original player masters audio/timeline.++ The small MediaPlayer-compatible surface keeps range playback, prewarming,+ and two-up comparison independent of the codec used for final exports.+ A single decoder thread owns each stream; seeks cancel old work immediately.+ """+ sourceChanged = Signal()+ videoOutputChanged = Signal()+ loopsChanged = Signal()+ positionChanged = Signal(int)+ durationChanged = Signal(int)+ videoFpsChanged = Signal()+ mediaStatusChanged = Signal(int)+ playbackStateChanged = Signal(int)+ errorOccurred = Signal(int, str)+ errorStringChanged = Signal()++ def __init__(self, parent=None):+ super().__init__(parent)+ self._source, self._output, self._sink = QUrl(), None, None+ self._loops, self._position, self._duration = 1, 0, 0+ self._video_fps = 0.0+ self._status, self._state, self._error = 0, 0, ""+ self._condition = threading.Condition()+ self._queue = deque()+ self._generation = 0+ self._request = None+ self._controller = None+ self._closed = False+ self._primed = False+ self._finished = False+ self._last_frame = QVideoFrame()+ self._clock = (time.monotonic(), 0)+ self._timer = QTimer(self)+ self._timer.setInterval(5)+ self._timer.timeout.connect(self._tick)+ self._thread = threading.Thread(target=self._decode_loop, name="preview-playback", daemon=True)+ self._thread.start()+ # QML objects are released before the application, including tests.+ self.destroyed.connect(lambda *_: self.close())+ from PySide6.QtCore import QCoreApplication+ if QCoreApplication.instance():+ QCoreApplication.instance().aboutToQuit.connect(self.close)++ def _set_source(self, value):+ value = QUrl(value)+ if value == self._source:+ return+ self._source = value+ self._set_state(2)+ self._set_position_value(0)+ self._duration = 0+ self.durationChanged.emit(0)+ if self._video_fps:+ self._video_fps = 0.0+ self.videoFpsChanged.emit()+ self._error = ""+ self.errorStringChanged.emit()+ self._last_frame = QVideoFrame()+ if self._sink:+ self._sink.setVideoFrame(self._last_frame)+ self._set_status(1 if not value.isEmpty() else 0)+ self._restart()+ self.sourceChanged.emit()++ def _set_output(self, output):+ self._output = output+ self._sink = output.property("videoSink") if output is not None else None+ if self._sink and self._last_frame.isValid():+ self._sink.setVideoFrame(self._last_frame)+ self.videoOutputChanged.emit()++ def _set_loops(self, value):+ self._loops = int(value)+ self.loopsChanged.emit()++ source = Property(QUrl, lambda self: self._source, _set_source, notify=sourceChanged)+ videoOutput = Property(QObject, lambda self: self._output, _set_output, notify=videoOutputChanged)+ loops = Property(int, lambda self: self._loops, _set_loops, notify=loopsChanged)+ position = Property(int, lambda self: self._position, lambda self, v: self.seek(v), notify=positionChanged)+ duration = Property(int, lambda self: self._duration, notify=durationChanged)+ videoFps = Property(float, lambda self: self._video_fps, notify=videoFpsChanged)+ mediaStatus = Property(int, lambda self: self._status, notify=mediaStatusChanged)+ playbackState = Property(int, lambda self: self._state, notify=playbackStateChanged)+ errorString = Property(str, lambda self: self._error, notify=errorStringChanged)++ def _set_status(self, value):+ if self._status != value:+ self._status = value+ self.mediaStatusChanged.emit(value)++ def _set_state(self, value):+ if self._state != value:+ self._state = value+ self.playbackStateChanged.emit(value)++ def _set_position_value(self, value):+ if self._position != value:+ self._position = value+ self.positionChanged.emit(value)++ def _restart(self):+ with self._condition:+ if self._closed:+ return+ self._generation += 1+ if self._controller:+ self._controller.stop()+ self._queue.clear()+ self._primed = self._finished = False+ self._request = (self._generation, self._source.toLocalFile(), self._position)+ self._condition.notify_all()+ self._clock = (time.monotonic(), self._position)+ if not self._source.isEmpty():+ self._timer.start()+ else:+ self._timer.stop()++ @Slot(int)+ def seek(self, position):+ position = max(0, int(position))+ if self._duration:+ position = min(position, max(0, self._duration - 1))+ if position == self._position and self._status != 6:+ return+ self._set_position_value(position)+ self._restart()++ @Slot()+ def play(self):+ if self._source.isEmpty() or self._closed:+ return+ if self._status == 6:+ self.seek(0)+ if self._state != 1:+ self._clock = (time.monotonic(), self._position)+ self._set_state(1)+ self._timer.start()++ @Slot()+ def pause(self):+ self._set_state(2)+ if self._primed:+ self._timer.stop()++ @Slot()+ def stop(self):+ self.pause()+ self.seek(0)+ self._set_state(0)++ @Slot()+ def close(self):+ with self._condition:+ self._closed = True+ if self._controller:+ self._controller.stop()+ self._queue.clear()+ self._condition.notify_all()+ # Never wait for decoding on the GUI thread. Cancellation closes the+ # pipe, and the daemon releases its handles in the decoder's finally.++ def _enqueue(self, generation, kind, payload):+ with self._condition:+ while not self._closed and generation == self._generation and len(self._queue) >= 3:+ self._condition.wait()+ if self._closed or generation != self._generation:+ return False+ self._queue.append((kind, payload))+ return True++ def _decode_loop(self):+ while True:+ with self._condition:+ while not self._closed and self._request is None:+ self._condition.wait()+ if self._closed:+ return+ generation, path, position = self._request+ self._request = None+ controller = self._controller = JobController()+ if not path:+ continue+ try:+ metadata = probe_video(path, count_mode="metadata", controller=controller)+ if controller.cancel.is_set():+ continue+ self._enqueue(generation, "duration", round(float(metadata.get("duration") or 0) * 1000))+ fps = float(metadata.get("fps") or 0)+ self._enqueue(generation, "fps", fps if math.isfinite(fps) and fps > 0 else 0.0)+ self._decode(path, metadata, position, generation, controller)+ if not controller.cancel.is_set():+ self._enqueue(generation, "end", None)+ except Exception as exc:+ if not controller.cancel.is_set():+ self._enqueue(generation, "error", str(exc))++ def _decode(self, path, metadata, position, generation, controller):+ fps = float(metadata.get("fps") or 30)+ start = max(0, math.floor(position * fps / 1000) / fps - .002)+ space = "bt2020" if metadata.get("color_primaries") == "bt2020" else "bt709"+ # Only convert for the display: no compressed encoder, file or proxy.+ command = [str(FFMPEG), "-hide_banner", "-v", "error", "-nostdin", "-copyts", "-start_at_zero", "-ss", f"{start:.6f}",+ "-i", path, "-map", "0:v:0", "-an", "-sn", "-dn",+ "-vf", f"scale=out_color_matrix={space}:out_range=tv,format=p010le,pad=ceil(iw/2)*2:ceil(ih/2)*2",+ "-c:v", "rawvideo", "-pix_fmt", "p010le", "-fps_mode", "passthrough",+ "-f", "nut", "-write_index", "0", "pipe:1"]+ logs = BoundedLogBuffer(max_tail=15)+ process = subprocess.Popen(command, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE,+ stderr=subprocess.PIPE, creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))+ controller.register(process)+ reader = threading.Thread(target=drain_bounded_text, args=(process.stderr, logs), daemon=True)+ reader.start()+ container = None+ try:+ container = av.open(_PipeReader(process.stdout), format="nut")+ display_format = _display_format(metadata)+ # Demux raw packets only. FFmpeg and PyAV can use different raw+ # pixel-format tags; our explicit P010 layout needs no decoder.+ for raw in container.demux(video=0):+ if not raw.size or raw.pts is None:+ continue+ if controller.cancel.is_set():+ return+ timestamp = float(raw.pts * raw.time_base)+ duration = float(raw.duration * raw.time_base) if raw.duration else 1 / fps+ frame = _display_frame(bytes(raw), display_format, round(timestamp * 1000000), round(duration * 1000000))+ if not self._enqueue(generation, "frame", frame):+ return+ process.wait(timeout=5)+ reader.join(timeout=1)+ if process.returncode:+ raise RuntimeError("Preview decoding failed: " + "\n".join(logs.snapshot()))+ finally:+ if process.poll() is None:+ process.kill()+ process.wait(timeout=5)+ if container:+ container.close()+ reader.join(timeout=1)+ controller.unregister(process)+ process.stdout.close()+ process.stderr.close()++ def _tick(self):+ if self._closed:+ self._timer.stop()+ return+ playing = self._state == 1+ now = time.monotonic()+ target = self._clock[1] + (now - self._clock[0]) * 1000 if playing and self._primed else self._position+ with self._condition:+ while self._queue:+ kind, payload = self._queue[0]+ if kind == "frame" and self._primed and (not playing or payload.startTime() / 1000 > target + 2):+ break+ self._queue.popleft()+ self._condition.notify_all()+ if kind == "duration":+ self._duration = payload+ self.durationChanged.emit(payload)+ elif kind == "fps":+ if self._video_fps != payload:+ self._video_fps = payload+ self.videoFpsChanged.emit()+ elif kind == "frame":+ self._last_frame = payload+ if self._sink:+ self._sink.setVideoFrame(payload)+ if not self._primed:+ self._primed = True+ self._clock = (now, self._position)+ self._set_status(2)+ elif kind == "end":+ self._finished = True+ elif kind == "error":+ self._error = payload+ self.errorStringChanged.emit()+ self._set_status(7)+ self._set_state(0)+ self.errorOccurred.emit(2, payload)+ self._timer.stop()+ return+ # A loaded/error notification can synchronously play, pause or seek+ # from QML. Honor that new state instead of the state at tick entry.+ playing = self._state == 1+ target = self._clock[1] + (time.monotonic() - self._clock[0]) * 1000+ if playing and self._primed:+ self._set_position_value(min(self._duration, round(target)))+ if self._finished and self._position >= self._duration:+ if self._loops < 0:+ self.seek(0)+ else:+ self._set_status(6)+ self._set_state(0)+ self._timer.stop()+ elif self._primed:+ self._timer.stop()diff --git a/src/desktop/qml/Main.qml b/src/desktop/qml/Main.qmlindex 510ff2a..a2a0738 100644--- a/src/desktop/qml/Main.qml+++ b/src/desktop/qml/Main.qml@@ -5,19 +5,22 @@ import QtQuick.Controls as QQC2import "."import "components"import "views"+import "controls"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)+ // Python applies the saved rectangle once before creating the native+ // window. Live geometry bindings would undo OS resizing and snapping.+ width: 1440+ height: 920minimumWidth: 1080minimumHeight: 700- // Python reveals the fully prepared window in its saved state.+ // Python reveals the fully prepared window maximized.flags: Qt.Window | Qt.FramelessWindowHinttitle: "Visual Enhancer"color: Theme.bgBase+ LayoutMirroring.enabled: Qt.application.layoutDirection === Qt.RightToLeft+ LayoutMirroring.childrenInherit: truereadonly property var windowRef: appWindowproperty bool closeApproved: false@@ -216,7 +219,15 @@ Window {focus: truemodal: trueclosePolicy: QQC2.Popup.CloseOnEscape- standardButtons: QQC2.Dialog.Yes | QQC2.Dialog.No+ footer: Item {+ implicitHeight: 48+ Row {+ anchors.right: parent.right; anchors.rightMargin: 20+ anchors.verticalCenter: parent.verticalCenter; spacing: 8+ AppButton { text: qsTranslate("App", "No"); onClicked: closeDialog.reject() }+ AppButton { text: qsTranslate("App", "Yes"); variant: "danger"; onClicked: closeDialog.accept() }+ }+ }leftPadding: 20rightPadding: 20topPadding: 16@@ -225,7 +236,7 @@ Window {// Borderless custom header: the default Dialog title chrome draws// its own light separator line under the title.header: QQC2.Label {- text: "Operation still active"+ text: qsTranslate("App", "Operation still active")color: Theme.textPrimaryfont.family: Theme.fontFamilyfont.pixelSize: Theme.fontSizeTitle@@ -236,7 +247,7 @@ Window {bottomPadding: 4}contentItem: Text {- text: "A render, preview, scan, or Live session is still active. Cancel it and exit?"+ text: qsTranslate("App", "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 adiff --git a/src/desktop/qml/assets/icons/png/128/live_video.png b/src/desktop/qml/assets/icons/png/128/live_video.pngindex 792c9bc..24e5765 100644Binary files a/src/desktop/qml/assets/icons/png/128/live_video.png and b/src/desktop/qml/assets/icons/png/128/live_video.png differdiff --git a/src/desktop/qml/assets/icons/png/128/neural_rendering.png b/src/desktop/qml/assets/icons/png/128/neural_rendering.pngindex 7db8492..1a13f15 100644Binary files a/src/desktop/qml/assets/icons/png/128/neural_rendering.png and b/src/desktop/qml/assets/icons/png/128/neural_rendering.png differdiff --git a/src/desktop/qml/assets/icons/png/16/live_video.png b/src/desktop/qml/assets/icons/png/16/live_video.pngindex 9cea0f3..0f9b9a4 100644Binary files a/src/desktop/qml/assets/icons/png/16/live_video.png and b/src/desktop/qml/assets/icons/png/16/live_video.png differdiff --git a/src/desktop/qml/assets/icons/png/16/neural_rendering.png b/src/desktop/qml/assets/icons/png/16/neural_rendering.pngindex 06b6989..4a10a17 100644Binary files a/src/desktop/qml/assets/icons/png/16/neural_rendering.png and b/src/desktop/qml/assets/icons/png/16/neural_rendering.png differdiff --git a/src/desktop/qml/assets/icons/png/20/live_video.png b/src/desktop/qml/assets/icons/png/20/live_video.pngindex 19dcd7b..930913c 100644Binary files a/src/desktop/qml/assets/icons/png/20/live_video.png and b/src/desktop/qml/assets/icons/png/20/live_video.png differdiff --git a/src/desktop/qml/assets/icons/png/20/neural_rendering.png b/src/desktop/qml/assets/icons/png/20/neural_rendering.pngindex bc25164..b8a1e71 100644Binary files a/src/desktop/qml/assets/icons/png/20/neural_rendering.png and b/src/desktop/qml/assets/icons/png/20/neural_rendering.png differdiff --git a/src/desktop/qml/assets/icons/png/24/live_video.png b/src/desktop/qml/assets/icons/png/24/live_video.pngindex 961bb5b..33878f4 100644Binary files a/src/desktop/qml/assets/icons/png/24/live_video.png and b/src/desktop/qml/assets/icons/png/24/live_video.png differdiff --git a/src/desktop/qml/assets/icons/png/24/neural_rendering.png b/src/desktop/qml/assets/icons/png/24/neural_rendering.pngindex 857f204..2d2890f 100644Binary files a/src/desktop/qml/assets/icons/png/24/neural_rendering.png and b/src/desktop/qml/assets/icons/png/24/neural_rendering.png differdiff --git a/src/desktop/qml/assets/icons/png/256/live_video.png b/src/desktop/qml/assets/icons/png/256/live_video.pngindex e412f0c..670a9e3 100644Binary files a/src/desktop/qml/assets/icons/png/256/live_video.png and b/src/desktop/qml/assets/icons/png/256/live_video.png differdiff --git a/src/desktop/qml/assets/icons/png/256/neural_rendering.png b/src/desktop/qml/assets/icons/png/256/neural_rendering.pngindex 7e4ec4a..5a4dc03 100644Binary files a/src/desktop/qml/assets/icons/png/256/neural_rendering.png and b/src/desktop/qml/assets/icons/png/256/neural_rendering.png differdiff --git a/src/desktop/qml/assets/icons/png/32/live_video.png b/src/desktop/qml/assets/icons/png/32/live_video.pngindex 31aa672..2b2073b 100644Binary files a/src/desktop/qml/assets/icons/png/32/live_video.png and b/src/desktop/qml/assets/icons/png/32/live_video.png differdiff --git a/src/desktop/qml/assets/icons/png/32/neural_rendering.png b/src/desktop/qml/assets/icons/png/32/neural_rendering.pngindex 217476e..8b7709f 100644Binary files a/src/desktop/qml/assets/icons/png/32/neural_rendering.png and b/src/desktop/qml/assets/icons/png/32/neural_rendering.png differdiff --git a/src/desktop/qml/assets/icons/png/48/live_video.png b/src/desktop/qml/assets/icons/png/48/live_video.pngindex 745d1aa..769abff 100644Binary files a/src/desktop/qml/assets/icons/png/48/live_video.png and b/src/desktop/qml/assets/icons/png/48/live_video.png differdiff --git a/src/desktop/qml/assets/icons/png/48/neural_rendering.png b/src/desktop/qml/assets/icons/png/48/neural_rendering.pngindex 15d1252..0719bf0 100644Binary files a/src/desktop/qml/assets/icons/png/48/neural_rendering.png and b/src/desktop/qml/assets/icons/png/48/neural_rendering.png differdiff --git a/src/desktop/qml/assets/icons/png/64/live_video.png b/src/desktop/qml/assets/icons/png/64/live_video.pngindex f6adaaf..fc51f44 100644Binary files a/src/desktop/qml/assets/icons/png/64/live_video.png and b/src/desktop/qml/assets/icons/png/64/live_video.png differdiff --git a/src/desktop/qml/assets/icons/png/64/neural_rendering.png b/src/desktop/qml/assets/icons/png/64/neural_rendering.pngindex a54126f..a80ec08 100644Binary files a/src/desktop/qml/assets/icons/png/64/neural_rendering.png and b/src/desktop/qml/assets/icons/png/64/neural_rendering.png differdiff --git a/src/desktop/qml/components/BatchQueueDrawer.qml b/src/desktop/qml/components/BatchQueueDrawer.qmlindex 46c76d1..ffa77ce 100644--- a/src/desktop/qml/components/BatchQueueDrawer.qml+++ b/src/desktop/qml/components/BatchQueueDrawer.qml@@ -1,79 +1,260 @@+pragma ComponentBehavior: Bound+import QtQuick+import QtQuick.Controls.Basic as QQC2import QtQuick.Dialogsimport ".."import "../controls"Rectangle {id: drawer+ objectName: "batchQueueDrawer"property var appBridge: nullproperty var queueModel: null- property bool collapsed: false+ property bool imageQueue: false+ property bool collapsed: true+ property int previousFileCount: 0property bool hidden: false- property int expandedHeight: appBridge ? appBridge.queueHeight : 190+ property int expandedHeight: appBridge ? appBridge.queueHeight : 330++ readonly property bool canModify: appBridge ? appBridge.canModifyQueue : true+ readonly property int fileCount: queueModel ? queueModel.count : 0+ readonly property int maximumHeight: Math.max(180, Math.min(720, parent ? parent.height - 180 : 720))+ readonly property bool showFps: !imageQueue && width >= 1040+ readonly property bool showRemaining: width >= 790+ readonly property bool showCompleted: width >= 900+ readonly property int inset: 12+ readonly property int columnGap: 12+ readonly property int numberWidth: 28+ readonly property int fpsWidth: 52+ readonly property int remainingWidth: 80+ readonly property int completedWidth: 84+ readonly property int statusWidth: 96+ readonly property int actionsWidth: 28+ readonly property real tableWidth: Math.max(0, width - inset * 2 - 10)+ readonly property int columnCount: 5 + (showFps ? 1 : 0) + (showRemaining ? 1 : 0) + (showCompleted ? 1 : 0)+ readonly property real flexibleWidth: Math.max(0, tableWidth - numberWidth - statusWidth - actionsWidth+ - (showFps ? fpsWidth : 0) - (showRemaining ? remainingWidth : 0)+ - (showCompleted ? completedWidth : 0) - columnGap * (columnCount - 1))+ readonly property real fileWidth: Math.floor(flexibleWidth * 0.57)+ readonly property real progressWidth: flexibleWidth - fileWidth+ readonly property color processingColor: Qt.lighter(Theme.accent, 1.5)++ // Show newly added files, then leave manual collapse intact until another+ // addition. Empty queues reclaim the viewport space automatically.+ onFileCountChanged: {+ if (fileCount === 0 || fileCount > previousFileCount)+ collapsed = fileCount === 0+ previousFileCount = fileCount+ }+ onQueueModelChanged: {+ collapsed = !queueModel || queueModel.count === 0+ previousFileCount = queueModel ? queueModel.count : 0+ }+ Component.onCompleted: {+ collapsed = fileCount === 0+ previousFileCount = fileCount+ }- height: hidden ? 0 : (collapsed ? 36 : expandedHeight)+ height: hidden ? 0 : (collapsed ? header.height : Math.min(maximumHeight, Math.max(180, expandedHeight)))visible: !hidden- color: Theme.bgSurface+ color: Theme.bgInputborder.color: Theme.borderSubtleborder.width: 1+ clip: true+ Behavior on height {+ enabled: !resizeHandle.pressed+ NumberAnimation { duration: Theme.animFast; easing.type: Easing.OutQuad }+ }- Behavior on height { NumberAnimation { duration: Theme.animFast; easing.type: Easing.OutQuad } }+ function clockTime(seconds, full) {+ if (!isFinite(seconds) || seconds < 0) return "—"+ var value = Math.max(0, Math.ceil(seconds))+ var hours = Math.floor(value / 3600)+ var minutes = Math.floor(value / 60) % 60+ var tail = String(value % 60).padStart(2, "0")+ if (full || hours > 0) return String(hours).padStart(2, "0") + ":" + String(minutes).padStart(2, "0") + ":" + tail+ return String(minutes).padStart(2, "0") + ":" + tail+ }+ function durationText(seconds) {+ var value = Math.max(0, Math.ceil(seconds))+ if (value < 60) return qsTranslate("App", "%1 s").arg(value)+ var minutes = Math.floor(value / 60) % 60+ var hours = Math.floor(value / 3600)+ if (hours > 0) return qsTranslate("App", "%1 h %2 min").arg(hours).arg(minutes)+ return qsTranslate("App", "%1 min %2 s").arg(minutes).arg(value % 60)+ }+ function fileSize(bytes) {+ if (bytes <= 0) return ""+ var units = ["B", "KB", "MB", "GB", "TB"]+ var unit = Math.min(4, Math.floor(Math.log(bytes) / Math.log(1024)))+ return (bytes / Math.pow(1024, unit)).toFixed(unit > 1 ? 1 : 0) + " " + units[unit]+ }++ component ColumnHeading: Text {+ height: columnHeader.height+ verticalAlignment: Text.AlignVCenter+ font.family: Theme.fontFamily; font.pixelSize: Theme.fontSizeSmall; font.weight: Font.Medium+ color: Theme.textSecondary+ elide: Text.ElideRight+ }+ component MetricText: Text {+ anchors.horizontalCenter: parent.horizontalCenter+ font.family: Theme.monoFontFamily; font.pixelSize: Theme.fontSizeBody+ color: Theme.textPrimary+ }+ component MetricCaption: Text {+ anchors.horizontalCenter: parent.horizontalCenter+ font.family: Theme.fontFamily; font.pixelSize: 10+ color: Theme.textMuted+ }+ component QueueToolTip: QQC2.ToolTip {+ id: tip+ width: Math.min(480, implicitWidth)+ delay: 650+ padding: 8+ contentItem: Text {+ text: tip.text+ font.family: Theme.fontFamily; font.pixelSize: Theme.fontSizeSmall+ color: Theme.textPrimary; wrapMode: Text.Wrap+ }+ background: Rectangle { color: Theme.bgBase; radius: Theme.radiusSmall; border.color: Theme.borderActive }+ }+ component RowAction: QQC2.MenuItem {+ id: action+ property string menuIcon: ""+ implicitHeight: 36+ leftPadding: 12; rightPadding: 12+ contentItem: Row {+ spacing: 10+ opacity: action.enabled ? 1 : 0.4+ AppIcon { iconName: action.menuIcon; iconSize: 16; anchors.verticalCenter: parent.verticalCenter }+ Text {+ text: action.text; color: Theme.textPrimary+ font.family: Theme.fontFamily; font.pixelSize: Theme.fontSizeBody+ anchors.verticalCenter: parent.verticalCenter+ }+ }+ background: Rectangle { radius: Theme.radiusSmall; color: action.highlighted ? Theme.bgHover : "transparent" }+ }Rectangle {id: headeranchors.top: parent.top; anchors.left: parent.left; anchors.right: parent.right- height: 36; color: "transparent"+ height: 44; color: Theme.bgSurfaceRow {- anchors.left: parent.left; anchors.leftMargin: 12; anchors.verticalCenter: parent.verticalCenter; spacing: 8- AppIcon { iconName: "queue"; iconSize: 16; color: Theme.textPrimary; anchors.verticalCenter: parent.verticalCenter }- 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 }- AppIconButton { iconName: "add_file"; buttonSize: 24; tooltipText: "Add files"; enabled: appBridge ? appBridge.canModifyQueue : true; onClicked: fileDialog.open() }- AppIconButton { iconName: "add_folder"; buttonSize: 24; tooltipText: "Add folder"; enabled: appBridge ? appBridge.canModifyQueue : true; onClicked: folderDialog.open() }- AppIconButton { iconName: "clear_done"; buttonSize: 24; tooltipText: "Clear completed items"; enabled: queueModel && queueModel.count > 0 && (appBridge ? appBridge.canModifyQueue : true); onClicked: { if (appBridge) appBridge.clearCompletedQueueItems() } }- AppIconButton { iconName: "clear_all"; buttonSize: 24; tooltipText: "Clear all items"; enabled: queueModel && queueModel.count > 0 && (appBridge ? appBridge.canModifyQueue : true); onClicked: { if (appBridge) appBridge.clearActiveQueue() } }+ anchors.left: parent.left; anchors.leftMargin: 16; anchors.verticalCenter: parent.verticalCenter+ spacing: 10+ AppIcon { iconName: "queue"; iconSize: 18; color: Theme.textPrimary; anchors.verticalCenter: parent.verticalCenter }+ Text {+ text: qsTranslate("App", "Batch Queue"); font.family: Theme.fontFamily; font.pixelSize: Theme.fontSizeSubtitle+ font.weight: Font.DemiBold; color: Theme.textPrimary; anchors.verticalCenter: parent.verticalCenter+ }+ AppBadge {+ text: drawer.fileCount + (drawer.fileCount === 1 ? qsTranslate("App", " file") : qsTranslate("App", " files"))+ variant: drawer.fileCount > 0 ? "accent" : "neutral"+ anchors.verticalCenter: parent.verticalCenter+ }}- AppIconButton {- anchors.right: parent.right; anchors.rightMargin: 10; anchors.verticalCenter: parent.verticalCenter- iconName: drawer.collapsed ? "chevron_up" : "chevron_down"- tooltipText: drawer.collapsed ? "Expand queue" : "Collapse queue"- onClicked: drawer.collapsed = !drawer.collapsed+ Row {+ anchors.right: parent.right; anchors.rightMargin: 12; anchors.verticalCenter: parent.verticalCenter+ spacing: 4+ AppIconButton { objectName: "queueAddFiles"; iconName: "add_file"; buttonSize: 28; tooltipText: qsTranslate("App", "Add files"); enabled: drawer.canModify; onClicked: fileDialog.open() }+ AppIconButton { iconName: "add_folder"; buttonSize: 28; tooltipText: qsTranslate("App", "Add folder"); enabled: drawer.canModify; onClicked: folderDialog.open() }+ Rectangle { width: 1; height: 16; color: Theme.borderDefault; anchors.verticalCenter: parent.verticalCenter }+ AppIconButton {+ iconName: "retry"; buttonSize: 28; tooltipText: qsTranslate("App", "Reset failed and cancelled items for retry")+ enabled: drawer.fileCount > 0 && drawer.canModify+ onClicked: { if (drawer.appBridge) drawer.appBridge.retryFailedQueueItems() }+ }+ AppIconButton {+ iconName: "clear_done"; buttonSize: 28; tooltipText: qsTranslate("App", "Clear completed items")+ enabled: drawer.fileCount > 0 && drawer.canModify+ onClicked: { if (drawer.appBridge) drawer.appBridge.clearCompletedQueueItems() }+ }+ AppIconButton {+ iconName: "clear_all"; buttonSize: 28; tooltipText: qsTranslate("App", "Clear all items")+ enabled: drawer.fileCount > 0 && drawer.canModify+ onClicked: { if (drawer.appBridge) drawer.appBridge.clearActiveQueue() }+ }+ Rectangle { width: 1; height: 16; color: Theme.borderDefault; anchors.verticalCenter: parent.verticalCenter }+ AppIconButton {+ objectName: "queueCollapse"+ iconName: drawer.collapsed ? "chevron_up" : "chevron_down"; buttonSize: 28+ tooltipText: drawer.collapsed ? qsTranslate("App", "Expand queue") : qsTranslate("App", "Collapse queue")+ onClicked: drawer.collapsed = !drawer.collapsed+ }+ }+ Rectangle { anchors.bottom: parent.bottom; width: parent.width; height: 1; color: Theme.borderSubtle }+ }++ Rectangle {+ id: columnHeader+ objectName: "queueColumnHeader"+ anchors.top: header.bottom; anchors.left: parent.left; anchors.right: parent.right+ height: drawer.collapsed ? 0 : 30; visible: !drawer.collapsed; color: Theme.bgInputHover+ Row {+ x: drawer.inset; width: drawer.tableWidth; spacing: drawer.columnGap+ ColumnHeading { width: drawer.numberWidth; text: "#"; horizontalAlignment: Text.AlignHCenter }+ ColumnHeading { width: drawer.fileWidth; text: qsTranslate("App", "Thumbnail / File") }+ ColumnHeading { width: drawer.progressWidth; text: qsTranslate("App", "Job progress") }+ ColumnHeading { width: drawer.fpsWidth; text: "FPS"; visible: drawer.showFps; horizontalAlignment: Text.AlignHCenter }+ ColumnHeading { width: drawer.remainingWidth; text: qsTranslate("App", "Remaining"); visible: drawer.showRemaining; horizontalAlignment: Text.AlignHCenter }+ ColumnHeading { width: drawer.completedWidth; text: qsTranslate("App", "Completed in"); visible: drawer.showCompleted; horizontalAlignment: Text.AlignHCenter }+ ColumnHeading { width: drawer.statusWidth; text: qsTranslate("App", "Status"); horizontalAlignment: Text.AlignHCenter }+ Item { width: drawer.actionsWidth; height: columnHeader.height }}- Rectangle { anchors.bottom: parent.bottom; anchors.left: parent.left; anchors.right: parent.right; height: 1; color: Theme.borderSubtle }+ Rectangle { anchors.bottom: parent.bottom; width: parent.width; height: 1; color: Theme.borderSubtle }}ListView {id: queueListobjectName: "batchQueueList"- 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- flickableDirection: Flickable.HorizontalFlick+ anchors.top: columnHeader.bottom; anchors.left: parent.left; anchors.right: parent.right; anchors.bottom: parent.bottom+ anchors.bottomMargin: 1+ clip: true; spacing: 0+ orientation: ListView.Vertical+ flickableDirection: Flickable.VerticalFlickboundsBehavior: Flickable.StopAtBounds- pressDelay: 120- synchronousDrag: true- visible: !drawer.collapsed; model: drawer.queueModel-+ visible: !drawer.collapsed+ model: drawer.queueModel+ reuseItems: true; cacheBuffer: 168+ currentIndex: drawer.queueModel ? drawer.queueModel.selectedIndex : -1WheelHandler {target: null- enabled: queueList.contentWidth > queueList.width+ enabled: queueList.contentHeight > queueList.heightonWheel: (event) => {- var delta = event.pixelDelta.x || event.pixelDelta.y- if (!delta) delta = event.angleDelta.x || event.angleDelta.y+ var delta = event.pixelDelta.y || event.angleDelta.y / 120 * 48if (!delta) return- var left = queueList.originX- var right = left + Math.max(0, queueList.contentWidth - queueList.width)- queueList.contentX = Math.max(left, Math.min(right, queueList.contentX - delta))+ queueList.cancelFlick()+ var top = queueList.originY+ var bottom = top + Math.max(0, queueList.contentHeight - queueList.height)+ queueList.contentY = Math.max(top, Math.min(bottom, queueList.contentY - delta))event.accepted = true}}+ QQC2.ScrollBar.vertical: QQC2.ScrollBar {+ id: queueScrollBar+ width: 8; policy: QQC2.ScrollBar.AsNeeded; minimumSize: 0.08+ visible: queueList.contentHeight > queueList.height+ contentItem: Rectangle {+ implicitWidth: 4; radius: 2+ color: queueScrollBar.pressed ? Theme.textSecondary : Theme.borderActive+ opacity: queueScrollBar.active || queueScrollBar.hovered ? 1 : 0.65+ }+ background: Rectangle { color: "transparent" }+ }+ onCurrentIndexChanged: { if (currentIndex >= 0) positionViewAtIndex(currentIndex, ListView.Contain) }+ onModelChanged: contentY = originYdelegate: Rectangle {- id: itemCard+ id: queueRow+ objectName: "batchQueueRow"required property int indexrequired property string fileNamerequired property string inputPathrequired property string outputPath- required property string state+ required property string itemStaterequired property real progressrequired property string detailrequired property real elapsedSeconds@@ -81,91 +262,332 @@ Rectangle {required property string outputDimensionsrequired property string thumbnailUrlrequired 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-+ required property real fileSizeBytes+ required property real durationSeconds+ required property int frameCount+ required property int processedFrames+ required property int processingTotalFrames+ required property real processingFps+ required property real remainingSeconds+ readonly property bool running: itemState === "Running"+ readonly property bool complete: itemState === "Completed" || itemState === "CompletedWithWarnings"+ readonly property bool failed: itemState === "Failed"+ readonly property bool stopped: itemState === "Cancelled" || itemState === "Skipped"+ readonly property real fraction: complete ? 1 : Math.max(0, Math.min(1, progress))+ readonly property color stateColor: failed ? Theme.danger : (complete ? Theme.success : (running ? drawer.processingColor : (stopped ? Theme.warning : Theme.textSecondary)))+ readonly property string statusText: qsTranslate("App", running ? "Processing" : (complete ? "Completed" : (failed ? "Error" : (stopped ? itemState : "Waiting"))))+ readonly property string progressTitle: {+ if (failed) return qsTranslate("App", "Failed")+ if (complete) return qsTranslate("App", "Saved and verified")+ if (stopped) return itemState === "Skipped" ? qsTranslate("App", "Skipped before processing") : qsTranslate("App", "Stopped by user")+ if (!running) return qsTranslate("App", "Waiting to start")+ var stage = detail.match(/\bStage\s+(\d+)\s+of\s+(\d+)\b/i)+ return stage ? qsTranslate("App", "Processing Stage %1 of %2").arg(stage[1]).arg(stage[2]) : qsTranslate("App", "Processing")+ }+ readonly property string metadataText: {+ var parts = []+ if (inputDimensions) parts.push(inputDimensions.replace("×", " × "))+ if (!drawer.imageQueue && frameCount > 0) parts.push(frameCount.toLocaleString(Qt.locale("en_US"), "f", 0) + " frames")+ var size = drawer.fileSize(fileSizeBytes)+ if (size) parts.push(size)+ return parts.join(" · ") || (drawer.imageQueue ? "Image" : "Video")+ }+ width: queueList.width; height: 84+ color: selected ? Theme.bgSelected : (rowMouse.containsMouse ? Theme.bgInputHover : (index % 2 ? Qt.darker(Theme.bgInput, 1.08) : Theme.bgInput))+ activeFocusOnTab: drawer.canModify+ Accessible.role: Accessible.ListItem+ Accessible.name: fileName + ", " + statusText + ", " + Math.round(fraction * 100) + " percent"+ Keys.onReturnPressed: { if (drawer.canModify && drawer.appBridge) drawer.appBridge.selectQueueItem(index) }+ Keys.onSpacePressed: { if (drawer.canModify && drawer.appBridge) drawer.appBridge.selectQueueItem(index) }+ Keys.onMenuPressed: rowMenu.openForButton()+ ListView.onPooled: rowMenu.close()+ ListView.onReused: rowMenu.close()+ Connections {+ target: queueList+ function onContentYChanged() { rowMenu.close() }+ }+ Rectangle { width: 3; height: parent.height - 1; color: Theme.accent; visible: queueRow.selected }+ Rectangle { anchors.bottom: parent.bottom; width: parent.width; height: 1; color: Theme.borderSubtle }+ Rectangle { anchors.fill: parent; color: "transparent"; border.color: Theme.accent; visible: queueRow.activeFocus }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) }+ id: rowMouse+ anchors.fill: parent; hoverEnabled: true; acceptedButtons: Qt.LeftButton | Qt.RightButton+ cursorShape: drawer.canModify ? Qt.PointingHandCursor : Qt.ArrowCursor+ onClicked: (mouse) => {+ if (mouse.button === Qt.RightButton) rowMenu.popup(rowMouse, mouse.x, mouse.y)+ else if (drawer.canModify && drawer.appBridge) drawer.appBridge.selectQueueItem(queueRow.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 }+ x: drawer.inset; width: drawer.tableWidth; height: parent.height - 1; spacing: drawer.columnGap+ Text {+ width: drawer.numberWidth; height: parent.height; text: queueRow.index + 1+ horizontalAlignment: Text.AlignHCenter; verticalAlignment: Text.AlignVCenter+ font.family: Theme.monoFontFamily; font.pixelSize: Theme.fontSizeBody+ color: queueRow.selected ? Theme.textPrimary : Theme.textMuted}-- 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; iconName: "trash"; buttonSize: 20; tooltipText: "Remove from queue"- visible: appBridge ? appBridge.canModifyQueue : true- onClicked: { if (appBridge) appBridge.removeQueueItem(itemCard.index) }+ Item {+ width: drawer.fileWidth; height: parent.height+ Rectangle {+ id: thumbnail+ width: drawer.width >= 1000 ? 90 : 76; height: 54+ anchors.verticalCenter: parent.verticalCenter; radius: Theme.radiusSmall; clip: true+ color: queueRow.failed ? Theme.dangerBg : Theme.bgBase+ border.width: 1+ border.color: queueRow.failed ? Qt.rgba(Theme.danger.r, Theme.danger.g, Theme.danger.b, 0.5) : Theme.borderSubtle+ Image {+ id: thumbnailImage+ anchors.fill: parent; anchors.margins: 1+ source: queueRow.thumbnailUrl; sourceSize: Qt.size(180, 108)+ // Posters are decoded in a worker; the memory provider is cheap to read.+ fillMode: Image.PreserveAspectCrop; asynchronous: false+ opacity: queueRow.failed ? 0.35 : 1+ }+ AppIcon {+ anchors.centerIn: parent+ iconName: queueRow.failed ? "error" : (drawer.imageQueue ? "image_file" : "video_file")+ iconSize: queueRow.failed ? 26 : 22; color: queueRow.failed ? Theme.danger : Theme.textMuted+ visible: queueRow.failed || thumbnailImage.status !== Image.Ready+ }+ Rectangle {+ anchors.right: parent.right; anchors.bottom: parent.bottom; anchors.margins: 3+ width: durationLabel.implicitWidth + 8; height: 17; radius: 3; color: "#D90F0F11"+ visible: !drawer.imageQueue && queueRow.durationSeconds > 0+ Text {+ id: durationLabel+ anchors.centerIn: parent; text: drawer.clockTime(queueRow.durationSeconds, false)+ font.family: Theme.monoFontFamily; font.pixelSize: 10; color: Theme.textPrimary+ }+ }+ }+ Column {+ anchors.left: thumbnail.right; anchors.leftMargin: 12; anchors.right: parent.right+ anchors.verticalCenter: parent.verticalCenter; spacing: 6+ Text {+ width: parent.width; text: queueRow.fileName; elide: Text.ElideMiddle+ font.family: Theme.fontFamily; font.pixelSize: Theme.fontSizeLabel; font.weight: Font.Medium+ color: queueRow.failed ? Theme.dangerHover : Theme.textPrimary+ }+ Text {+ width: parent.width; text: queueRow.metadataText; elide: Text.ElideRight+ font.family: Theme.fontFamily; font.pixelSize: Theme.fontSizeSmall; color: Theme.textSecondary}}- 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")))+ HoverHandler { id: fileHover }+ QueueToolTip { visible: fileHover.hovered; text: queueRow.inputPath + "\n" + queueRow.metadataText }+ }+ Item {+ width: drawer.progressWidth; height: parent.height+ Column {+ anchors.verticalCenter: parent.verticalCenter; width: parent.width; spacing: 6+ Text {+ width: parent.width; text: queueRow.progressTitle; elide: Text.ElideRight+ font.family: Theme.fontFamily; font.pixelSize: Theme.fontSizeSmall+ color: queueRow.failed ? Theme.dangerHover : (queueRow.running ? Theme.textPrimary : Theme.textSecondary)+ }+ Rectangle {+ width: parent.width; height: 6; radius: 3; color: Theme.bgBase; border.color: Theme.borderSubtle+ Rectangle {+ width: Math.max(height, parent.width * queueRow.fraction); height: parent.height; radius: 3+ visible: queueRow.fraction > 0+ color: queueRow.failed ? Theme.danger : (queueRow.complete ? Theme.success : (queueRow.stopped ? Theme.warning : Theme.accent))+ Behavior on width { NumberAnimation { duration: Theme.animFast } }+ }+ }+ Row {+ width: parent.width; spacing: 8+ Text {+ id: percentLabel+ text: Math.floor(queueRow.fraction * 100) + "%"+ font.family: Theme.monoFontFamily; font.pixelSize: Theme.fontSizeSmall+ color: queueRow.complete ? Theme.success : Theme.textPrimary+ }+ Text {+ width: Math.max(0, parent.width - percentLabel.width - parent.spacing)+ text: {+ if (!drawer.showCompleted && queueRow.complete && queueRow.elapsedSeconds > 0)+ return qsTranslate("App", "Completed in %1").arg(drawer.clockTime(queueRow.elapsedSeconds, false))+ if (!drawer.showRemaining && queueRow.running && queueRow.remainingSeconds >= 0)+ return qsTranslate("App", "~%1 remaining").arg(drawer.clockTime(queueRow.remainingSeconds, false))+ if (queueRow.complete && !drawer.imageQueue && queueRow.frameCount > 0)+ return qsTranslate("App", "%1 source frames").arg(queueRow.frameCount.toLocaleString(Qt.locale(), "f", 0))+ if (queueRow.outputDimensions) return qsTranslate("App", "Output %1").arg(queueRow.outputDimensions)+ return queueRow.running ? qsTranslate("App", "Overall job progress") : ""+ }+ elide: Text.ElideRight; font.family: Theme.fontFamily; font.pixelSize: Theme.fontSizeSmall; color: Theme.textSecondary+ }}- 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 }+ HoverHandler { id: progressHover }+ QueueToolTip {+ visible: progressHover.hovered && queueRow.detail !== ""+ text: {+ var lines = [queueRow.detail]+ if (queueRow.running && queueRow.processingFps > 0)+ lines.push(queueRow.processingFps.toFixed(1) + qsTranslate("App", " input FPS"))+ if (queueRow.running && queueRow.remainingSeconds >= 0)+ lines.push(qsTranslate("App", "Estimated time to finish this job, including export: %1").arg(drawer.clockTime(queueRow.remainingSeconds, true)))+ if (queueRow.complete && queueRow.elapsedSeconds > 0)+ lines.push(qsTranslate("App", "Completed in %1").arg(drawer.clockTime(queueRow.elapsedSeconds, true)))+ return lines.join("\n")+ }+ }+ }+ Item {+ width: drawer.fpsWidth; height: parent.height; visible: drawer.showFps+ Column {+ anchors.centerIn: parent; spacing: 4+ MetricText { text: queueRow.running && queueRow.processingFps > 0 ? queueRow.processingFps.toFixed(1) : "—" }+ MetricCaption { text: "FPS" }}- 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"; iconName: "reveal_in_explorer"; buttonHeight: 20; visible: itemCard.outputPath !== ""; onClicked: { if (appBridge) appBridge.openFolder(itemCard.outputPath) } }+ HoverHandler { id: fpsHover }+ QueueToolTip { visible: fpsHover.hovered; text: qsTranslate("App", "Measured input frames per second in the current stage") }+ }+ Item {+ width: drawer.remainingWidth; height: parent.height; visible: drawer.showRemaining+ Column {+ anchors.centerIn: parent; spacing: 4+ MetricText { text: queueRow.running && queueRow.remainingSeconds >= 0 ? "~" + drawer.clockTime(queueRow.remainingSeconds, false) : "—" }+ MetricCaption { text: queueRow.running && queueRow.remainingSeconds >= 0 ? qsTranslate("App", "estimated") : "" }+ }+ HoverHandler { id: remainingHover }+ QueueToolTip { visible: remainingHover.hovered; text: qsTranslate("App", "Estimated time to finish all processing stages and export for this file") }+ }+ Item {+ width: drawer.completedWidth; height: parent.height; visible: drawer.showCompleted+ Column {+ anchors.centerIn: parent; spacing: 4+ MetricText { text: queueRow.complete && queueRow.elapsedSeconds > 0 ? drawer.clockTime(queueRow.elapsedSeconds, false) : "—" }+ MetricCaption { text: queueRow.complete && queueRow.elapsedSeconds > 0 ? drawer.durationText(queueRow.elapsedSeconds) : "" }+ }+ }+ Item {+ width: drawer.statusWidth; height: parent.height+ Text {+ objectName: "queueStatusText"+ anchors.fill: parent+ horizontalAlignment: Text.AlignHCenter+ verticalAlignment: Text.AlignVCenter+ text: queueRow.statusText+ font.family: Theme.fontFamily; font.pixelSize: Theme.fontSizeBody+ font.weight: Font.Medium; color: queueRow.stateColor+ }+ HoverHandler { id: statusHover }+ QueueToolTip { visible: statusHover.hovered && queueRow.detail !== ""; text: queueRow.detail }+ }+ Item {+ width: drawer.actionsWidth; height: parent.height+ AppIconButton {+ id: actionButton+ objectName: "queueRowActions"+ anchors.centerIn: parent; buttonSize: 28; iconName: ""+ tooltipText: qsTranslate("App", "Actions for %1").arg(queueRow.fileName)+ showTooltip: !rowMenu.opened+ onClicked: rowMenu.openForButton()+ Column {+ anchors.centerIn: parent; spacing: 3+ Repeater { model: 3; Rectangle { width: 3; height: 3; radius: 1.5; color: Theme.textSecondary } }+ }+ }+ QQC2.Menu {+ id: rowMenu+ objectName: "queueRowMenu"+ parent: actionButton+ popupType: QQC2.Popup.Item+ margins: 8+ width: 210; padding: 4+ function openForButton() {+ // popup() changes the parent and coordinates. Set+ // them on every open so a previous right-click (or+ // recycled row) cannot displace the button menu.+ var overlay = QQC2.Overlay.overlay+ var top = actionButton.mapToItem(overlay, 0, 0).y+ var below = actionButton.height + 4+ var y = overlay && top + below + height > overlay.height - margins+ ? -height - 4 : below+ popup(actionButton, actionButton.width - width, y)+ }+ closePolicy: QQC2.Popup.CloseOnEscape | QQC2.Popup.CloseOnPressOutside+ background: Rectangle { color: Theme.bgSurface; radius: Theme.radiusMedium; border.color: Theme.borderActive }+ RowAction { text: qsTranslate("App", "Preview file"); menuIcon: "preview"; enabled: drawer.canModify; onTriggered: { if (drawer.appBridge) drawer.appBridge.selectQueueItem(queueRow.index) } }+ RowAction { text: qsTranslate("App", "Open source folder"); menuIcon: "folder"; onTriggered: { if (drawer.appBridge) drawer.appBridge.openFolder(queueRow.inputPath) } }+ RowAction { objectName: "queueRevealOutput"; text: qsTranslate("App", "Show output in Explorer"); menuIcon: "reveal_in_explorer"; enabled: queueRow.outputPath !== ""; onTriggered: { if (drawer.appBridge) drawer.appBridge.openFolder(queueRow.outputPath) } }+ QQC2.MenuSeparator { contentItem: Rectangle { implicitHeight: 1; color: Theme.borderSubtle } }+ RowAction { objectName: "queueRemoveItem"; text: qsTranslate("App", "Remove from queue"); menuIcon: "trash"; enabled: drawer.canModify; onTriggered: { if (drawer.appBridge) drawer.appBridge.removeQueueItem(queueRow.index) } }}}}}+ }+ Column {+ anchors.centerIn: queueList; width: Math.min(420, drawer.width - 40); spacing: 8+ visible: !drawer.collapsed && drawer.fileCount === 0+ AppIcon { iconName: "inbox_import"; iconSize: 26; color: Theme.textMuted; anchors.horizontalCenter: parent.horizontalCenter }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+ width: parent.width; text: drawer.imageQueue ? qsTranslate("App", "Your image queue is empty") : qsTranslate("App", "Your video queue is empty")+ horizontalAlignment: Text.AlignHCenter; font.family: Theme.fontFamily; font.pixelSize: Theme.fontSizeLabel; color: Theme.textPrimary+ }+ Text {+ width: parent.width; text: qsTranslate("App", "Add files, choose a folder, or drop media into the preview.")+ horizontalAlignment: Text.AlignHCenter; wrapMode: Text.WordWrap+ font.family: Theme.fontFamily; font.pixelSize: Theme.fontSizeSmall; color: Theme.textSecondary}}MouseArea {+ id: resizeHandle+ objectName: "queueResizeHandle"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 }+ height: 5; z: 100; visible: !drawer.collapsed && !drawer.hidden+ cursorShape: Qt.SizeVerCursor; hoverEnabled: true+ property real pressY: 0+ property real startHeight: 0+ onPressed: (mouse) => { pressY = mapToItem(drawer.parent, mouse.x, mouse.y).y; startHeight = drawer.height }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)+ var currentY = mapToItem(drawer.parent, mouse.x, mouse.y).y+ var value = Math.round(Math.max(180, Math.min(drawer.maximumHeight, startHeight + pressY - currentY)))+ if (drawer.appBridge) drawer.appBridge.queueHeight = value+ else drawer.expandedHeight = value}+ Rectangle { anchors.top: parent.top; width: parent.width; height: 2; color: Theme.accent; visible: resizeHandle.containsMouse || resizeHandle.pressed }+ }++ // File drops append to the workflow's Image and Video queues even when+ // this drawer already contains items. This target does not handle clicks.+ DropArea {+ id: queueDropArea+ objectName: "queueDropArea"+ anchors.fill: parent+ z: 200+ enabled: drawer.canModify+ onDropped: (drop) => {+ if (!drop.hasUrls || !drawer.appBridge) return+ var urls = []+ for (var i = 0; i < drop.urls.length; i++) urls.push(drop.urls[i].toString())+ drawer.appBridge.addFiles(urls)+ }+ }+ Rectangle {+ anchors.fill: parent+ z: 199+ color: "#220387C2"+ border.color: Theme.accent+ border.width: 2+ visible: queueDropArea.containsDrag}- FolderDialog { id: folderDialog; title: "Add Folder to Batch"; onAccepted: { if (appBridge) appBridge.addFiles([selectedFolder.toString()]) } }+ FolderDialog { id: folderDialog; title: qsTranslate("App", "Add Folder to Batch"); onAccepted: { if (drawer.appBridge) drawer.appBridge.addFiles([selectedFolder.toString()]) } }FileDialog {- id: fileDialog; title: "Add Files to Batch"; fileMode: FileDialog.OpenFiles; nameFilters: ["All Media Files (*.*)"]+ id: fileDialog+ title: qsTranslate("App", "Add Files to Batch"); fileMode: FileDialog.OpenFiles+ nameFilters: [qsTranslate("App", "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)+ if (!drawer.appBridge || selectedFiles.length === 0) return+ var urls = []+ for (var i = 0; i < selectedFiles.length; i++) urls.push(selectedFiles[i].toString())+ drawer.appBridge.addFiles(urls)}}}diff --git a/src/desktop/qml/components/ColoringControls.qml b/src/desktop/qml/components/ColoringControls.qmlindex 8f2aba4..f20f5db 100644--- a/src/desktop/qml/components/ColoringControls.qml+++ b/src/desktop/qml/components/ColoringControls.qml@@ -1,21 +1,41 @@import QtQuickimport QtQuick.Dialogs+import QtQuick.Layoutsimport ".."import "../controls"Column {id: rootproperty var appBridge: null+ property real playheadMs: 0property string lutPanel: "Color Adjustment"readonly property bool isImage: appBridge ? appBridge.nrMode === "Image" : true+ readonly property string autoFrameText: root.isImage ? qsTranslate("App", "Auto") : qsTranslate("App", "Auto 1 Frame")+ readonly property string autoFixedText: qsTranslate("App", "Auto Fixed Frames")+ readonly property real autoFrameWidth: Math.max(80, Math.ceil(frameAutoMetrics.advanceWidth) + 48)+ readonly property real autoFixedWidth: Math.max(80, Math.ceil(fixedAutoMetrics.advanceWidth) + 48)+ readonly property real autoButtonWidth: Math.max(autoFrameWidth, autoFixedWidth)width: parent ? parent.width : 320spacing: 12+ TextMetrics {+ id: frameAutoMetrics+ font.family: Theme.fontFamily+ font.pixelSize: Theme.fontSizeLabel+ text: root.autoFrameText+ }+ TextMetrics {+ id: fixedAutoMetrics+ font.family: Theme.fontFamily+ font.pixelSize: Theme.fontSizeLabel+ text: root.autoFixedText+ }+AppComboBox {width: parent.width- label: "Method"+ label: qsTranslate("App", "Method")model: root.isImage ? (appBridge ? appBridge.coloringModeChoices : [])- : [{label: "Apply LUT", value: "LUT"}]+ : [{label: qsTranslate("App", "Apply LUT"), value: "LUT"}]currentValue: root.isImage ? (appBridge ? appBridge.coloringMode : "Color Match") : "LUT"onActivated: value => {if (value === "LUT") root.lutPanel = "Color Adjustment"@@ -30,7 +50,7 @@ Column {AppComboBox {width: parent.width- label: "Match Colors From"+ label: qsTranslate("App", "Match Colors From")model: appBridge ? appBridge.colorMatchSourceChoices : []currentValue: appBridge ? appBridge.colorMatchSource : "Input Image"onActivated: value => { if (appBridge) appBridge.colorMatchSource = value }@@ -39,11 +59,11 @@ Column {AppFilePicker {width: parent.widthvisible: appBridge && appBridge.colorMatchSource === "Selected Image"- label: "Selected Reference Image"- placeholderText: "Choose a reference image"+ label: qsTranslate("App", "Selected Reference Image")+ placeholderText: qsTranslate("App", "Choose a reference image")selectedPath: appBridge ? appBridge.colorMatchReference : ""- nameFilters: ["Images (*.png *.jpg *.jpeg *.webp *.tif *.tiff *.bmp *.avif *.heic *.heif *.svg *.dng *.cr2 *.nef *.arw)",- "All Files (*.*)"]+ nameFilters: [qsTranslate("App", "Images (*.png *.jpg *.jpeg *.webp *.tif *.tiff *.bmp *.avif *.heic *.heif *.svg *.dng *.cr2 *.nef *.arw)"),+ qsTranslate("App", "All Files (*.*)")]onPathChanged: path => {if (appBridge) appBridge.setColorMatchReference(path)Qt.callLater(syncPath)@@ -66,10 +86,10 @@ Column {AppFilePicker {width: parent.widthvisible: root.lutPanel === "LUT File"- label: "LUT File (.cube)"- placeholderText: "Choose a 3D .cube LUT"+ label: qsTranslate("App", "LUT File (.cube)")+ placeholderText: qsTranslate("App", "Choose a 3D .cube LUT")selectedPath: appBridge ? appBridge.lutFile : ""- nameFilters: ["3D LUT Files (*.cube)", "All Files (*.*)"]+ nameFilters: [qsTranslate("App", "3D LUT Files (*.cube)"), qsTranslate("App", "All Files (*.*)")]onPathChanged: path => {if (appBridge) appBridge.setLutFile(path)Qt.callLater(syncPath)@@ -81,54 +101,87 @@ Column {spacing: 12visible: root.lutPanel === "Color Adjustment"- Item {+ AppComboBox {+ id: resolutionControl+ objectName: "coloring-lut-resolution"width: parent.width- height: resolutionControl.implicitHeight-- AppComboBox {- id: resolutionControl- objectName: "coloring-lut-resolution"- width: parent.width - resetButton.width - 8- height: implicitHeight- anchors.left: parent.left- label: "LUT Resolution"- model: appBridge ? appBridge.lutResolutionChoices : []- currentValue: appBridge ? appBridge.lutResolution : 33- onActivated: value => { if (appBridge) appBridge.lutResolution = value }- }-- AppButton {- id: resetButton- objectName: "coloring-reset-adjustments"- width: 92- anchors.right: parent.right- anchors.bottom: parent.bottom- text: "Reset"- iconName: "reset"- onClicked: { if (appBridge) appBridge.resetLutAdjustments() }- }+ label: qsTranslate("App", "LUT Resolution")+ model: appBridge ? appBridge.lutResolutionChoices : []+ currentValue: appBridge ? appBridge.lutResolution : 33+ onActivated: value => { if (appBridge) appBridge.lutResolution = value }}AppSlider {width: parent.width- label: "LUT Strength"+ label: qsTranslate("App", "LUT Strength")from: 0; to: 200; stepSize: 1; precision: 0; defaultValue: 100; unit: "%"value: appBridge ? appBridge.lutAdjustmentValues.lut_mix : 100onValueModified: v => { if (appBridge) appBridge.setLutAdjustment("lut_mix", v) }}- AppButton {- objectName: "coloring-auto-adjustments"+ GridLayout {+ id: autoButtonswidth: parent.width- text: appBridge && appBridge.lutAutoBusy ? "Analyzing…" : "Auto"- iconName: "quality_enhance"- enabled: appBridge && !!appBridge.previewInputUrl- && appBridge.canModifyQueue && !appBridge.lutAutoBusy- onClicked: { if (appBridge) appBridge.autoAdjustLut() }+ columnSpacing: 8+ rowSpacing: 8+ columns: !root.isImage && 2 * root.autoButtonWidth + columnSpacing > width ? 1 : 2++ AppButton {+ id: frameAutoButton+ objectName: "coloring-auto-adjustments"+ // Let the layout own width; AppButton's default binding+ // would reset it when the busy label changes.+ width: 0+ Layout.row: 0+ Layout.column: 0+ Layout.fillWidth: true+ Layout.minimumWidth: root.isImage ? root.autoFrameWidth : root.autoButtonWidth+ Layout.preferredWidth: root.isImage ? autoButtons.width - 100 : root.autoButtonWidth+ text: appBridge && appBridge.lutAutoBusy && appBridge.lutAutoMode === "frame"+ ? qsTranslate("App", "Analyzing…")+ : root.autoFrameText+ iconName: "quality_enhance"+ enabled: appBridge && !!appBridge.previewInputUrl+ && appBridge.canModifyQueue && !appBridge.lutAutoBusy && !appBridge.lutReferenceBusy+ onClicked: { if (appBridge) appBridge.autoAdjustLut(root.playheadMs) }+ }++ AppButton {+ id: fixedAutoButton+ objectName: "coloring-auto-fixed-frames"+ width: 0+ visible: !root.isImage+ Layout.row: autoButtons.columns === 1 ? 1 : 0+ Layout.column: autoButtons.columns === 1 ? 0 : 1+ Layout.fillWidth: true+ Layout.minimumWidth: root.autoButtonWidth+ Layout.preferredWidth: root.autoButtonWidth+ text: appBridge && appBridge.lutAutoBusy && appBridge.lutAutoMode === "fixed"+ ? qsTranslate("App", "Analyzing…") : root.autoFixedText+ iconName: "quality_enhance"+ enabled: frameAutoButton.enabled+ onClicked: { if (appBridge) appBridge.autoAdjustLutFixedFrames() }+ }++ AppButton {+ id: resetButton+ objectName: "coloring-reset-adjustments"+ width: 0+ Layout.row: root.isImage ? 0 : (autoButtons.columns === 1 ? 2 : 1)+ Layout.column: root.isImage ? 1 : 0+ Layout.columnSpan: root.isImage ? 1 : autoButtons.columns+ Layout.fillWidth: !root.isImage+ Layout.minimumWidth: implicitWidth+ Layout.preferredWidth: root.isImage ? 92 : autoButtons.width+ text: qsTranslate("App", "Reset")+ iconName: "reset"+ enabled: appBridge && appBridge.canModifyQueue && !appBridge.lutAutoBusy && !appBridge.lutReferenceBusy+ onClicked: { if (appBridge) appBridge.resetLutAdjustments() }+ }}Text {- text: "Light"+ text: qsTranslate("App", "Light")font.family: Theme.fontFamilyfont.pixelSize: Theme.fontSizeLabelfont.weight: Font.DemiBold@@ -137,13 +190,13 @@ Column {Repeater {model: [- {key: "lut_exposure", label: "Exposure", from: -3, to: 3, step: 0.05, precision: 2, unit: "EV"},- {key: "lut_contrast", label: "Contrast", from: -100, to: 100, step: 1, precision: 0, unit: "%"},- {key: "lut_highlights", label: "Highlights", from: -100, to: 100, step: 1, precision: 0, unit: "%"},- {key: "lut_shadows", label: "Shadows", from: -100, to: 100, step: 1, precision: 0, unit: "%"},- {key: "lut_whites", label: "Whites", from: -100, to: 100, step: 1, precision: 0, unit: "%"},- {key: "lut_blacks", label: "Blacks", from: -100, to: 100, step: 1, precision: 0, unit: "%"},- {key: "lut_midtones", label: "Midtones", from: -100, to: 100, step: 1, precision: 0, unit: "%"}+ {key: "lut_exposure", label: qsTranslate("App", "Exposure"), from: -3, to: 3, step: 0.05, precision: 2, unit: "EV"},+ {key: "lut_contrast", label: qsTranslate("App", "Contrast"), from: -100, to: 100, step: 1, precision: 0, unit: "%"},+ {key: "lut_highlights", label: qsTranslate("App", "Highlights"), from: -100, to: 100, step: 1, precision: 0, unit: "%"},+ {key: "lut_shadows", label: qsTranslate("App", "Shadows"), from: -100, to: 100, step: 1, precision: 0, unit: "%"},+ {key: "lut_whites", label: qsTranslate("App", "Whites"), from: -100, to: 100, step: 1, precision: 0, unit: "%"},+ {key: "lut_blacks", label: qsTranslate("App", "Blacks"), from: -100, to: 100, step: 1, precision: 0, unit: "%"},+ {key: "lut_midtones", label: qsTranslate("App", "Midtones"), from: -100, to: 100, step: 1, precision: 0, unit: "%"}]delegate: AppSlider {required property var modelData@@ -157,7 +210,7 @@ Column {}Text {- text: "Color"+ text: qsTranslate("App", "Color")font.family: Theme.fontFamilyfont.pixelSize: Theme.fontSizeLabelfont.weight: Font.DemiBold@@ -166,11 +219,11 @@ Column {Repeater {model: [- {key: "lut_temperature", label: "Temperature", from: -100, to: 100, unit: ""},- {key: "lut_tint", label: "Tint", from: -100, to: 100, unit: ""},- {key: "lut_hue", label: "Hue Shift", from: -180, to: 180, unit: "°"},- {key: "lut_vibrance", label: "Vibrance", from: -100, to: 100, unit: "%"},- {key: "lut_saturation", label: "Saturation", from: -100, to: 100, unit: "%"}+ {key: "lut_temperature", label: qsTranslate("App", "Temperature"), from: -100, to: 100, unit: ""},+ {key: "lut_tint", label: qsTranslate("App", "Tint"), from: -100, to: 100, unit: ""},+ {key: "lut_hue", label: qsTranslate("App", "Hue Shift"), from: -180, to: 180, unit: "°"},+ {key: "lut_vibrance", label: qsTranslate("App", "Vibrance"), from: -100, to: 100, unit: "%"},+ {key: "lut_saturation", label: qsTranslate("App", "Saturation"), from: -100, to: 100, unit: "%"}]delegate: AppSlider {required property var modelData@@ -185,11 +238,12 @@ Column {}AppButton {+ objectName: "coloring-save-lut"width: parent.width- text: appBridge && appBridge.lutSaveBusy ? "Saving LUT…" : "Save LUT"+ text: appBridge && appBridge.lutSaveBusy ? qsTranslate("App", "Saving LUT…") : qsTranslate("App", "Save LUT")iconName: "export"variant: "primary"- enabled: appBridge && !appBridge.lutSaveBusy+ enabled: appBridge && !appBridge.lutSaveBusy && !appBridge.lutReferenceBusy&& (root.lutPanel === "Color Adjustment" || !!appBridge.lutFile)onClicked: lutSaveDialog.open()}@@ -203,14 +257,40 @@ Column {font.pixelSize: Theme.fontSizeSmallcolor: Theme.textSecondary}++ AppFilePicker {+ objectName: "coloring-lut-reference-image"+ width: parent.width+ label: qsTranslate("App", "Reference Image")+ placeholderText: qsTranslate("App", "Choose an image to match its colors")+ selectedPath: appBridge ? appBridge.lutReferenceImage : ""+ enabled: appBridge && appBridge.canModifyQueue && !appBridge.lutAutoBusy+ nameFilters: [qsTranslate("App", "Images (*.png *.jpg *.jpeg *.webp *.tif *.tiff *.bmp *.avif *.heic *.heif *.svg *.dng *.cr2 *.nef *.arw)"),+ qsTranslate("App", "All Files (*.*)")]+ onPathChanged: path => {+ if (appBridge) appBridge.setLutReferenceImage(path)+ Qt.callLater(syncPath)+ }+ }++ Text {+ objectName: "coloring-lut-reference-status"+ width: parent.width+ visible: appBridge && appBridge.lutReferenceStatus !== ""+ text: appBridge ? appBridge.lutReferenceStatus : ""+ wrapMode: Text.WordWrap+ font.family: Theme.fontFamily+ font.pixelSize: Theme.fontSizeSmall+ color: appBridge && appBridge.lutReferenceBusy ? Theme.accent : Theme.textSecondary+ }}FileDialog {id: lutSaveDialog- title: "Save Graded 3D LUT"+ title: qsTranslate("App", "Save Graded 3D LUT")fileMode: FileDialog.SaveFiledefaultSuffix: "cube"- nameFilters: ["3D LUT Files (*.cube)"]+ nameFilters: [qsTranslate("App", "3D LUT Files (*.cube)")]onAccepted: { if (appBridge && selectedFile) appBridge.saveLut(selectedFile.toString()) }}}diff --git a/src/desktop/qml/components/CompositionCard.qml b/src/desktop/qml/components/CompositionCard.qmlindex 87f8b4c..ad4ef42 100644--- a/src/desktop/qml/components/CompositionCard.qml+++ b/src/desktop/qml/components/CompositionCard.qml@@ -7,7 +7,7 @@ AppCard {id: rootproperty var appBridge: null- title: "Composition & Masking"+ title: qsTranslate("App", "Composition & Masking")Column {width: parent.width@@ -19,7 +19,7 @@ AppCard {spacing: 8AppButton {- text: "Apply Detail-Only Preset"+ text: qsTranslate("App", "Apply Detail-Only Preset")iconName: "quality_enhance"width: parent.widthbuttonHeight: 28@@ -32,7 +32,7 @@ AppCard {// SlidersAppSlider {width: parent.width- label: "NR Color Strength"+ label: qsTranslate("App", "NR Color Strength")from: 0.0to: 1.0stepSize: 0.05@@ -43,7 +43,7 @@ AppCard {AppSlider {width: parent.width- label: "Tone Preservation"+ label: qsTranslate("App", "Tone Preservation")from: 0.0to: 1.0stepSize: 0.05@@ -54,7 +54,7 @@ AppCard {AppSlider {width: parent.width- label: "Face / Skin Protection"+ label: qsTranslate("App", "Face / Skin Protection")from: 0.0to: 1.0stepSize: 0.05@@ -65,7 +65,7 @@ AppCard {AppSlider {width: parent.width- label: "Grain Preservation"+ label: qsTranslate("App", "Grain Preservation")from: 0.0to: 1.0stepSize: 0.05@@ -76,7 +76,7 @@ AppCard {AppSlider {width: parent.width- label: "Mask Feather"+ label: qsTranslate("App", "Mask Feather")unit: "px"from: 0to: 128@@ -105,14 +105,14 @@ AppCard {spacing: 8AppButton {- text: "Load Custom Mask..."+ text: qsTranslate("App", "Load Custom Mask...")iconName: "load_mask"buttonHeight: 24onClicked: maskDialog.open()}AppButton {- text: "Clear Mask"+ text: qsTranslate("App", "Clear Mask")iconName: "clear_mask"buttonHeight: 24onClicked: {@@ -123,7 +123,7 @@ AppCard {Text {anchors.horizontalCenter: parent.horizontalCenter- text: appBridge ? appBridge.customMaskStatus : "No mask loaded"+ text: appBridge ? appBridge.customMaskStatus : qsTranslate("App", "No mask loaded")font.family: Theme.monoFontFamilyfont.pixelSize: Theme.fontSizeSmallcolor: Theme.textMuted@@ -134,8 +134,8 @@ AppCard {FileDialog {id: maskDialog- title: "Select Custom NR Mask"- nameFilters: ["Image Files (*.png *.jpg *.jpeg *.webp *.tiff *.bmp)", "All Files (*.*)"]+ title: qsTranslate("App", "Select Custom NR Mask")+ nameFilters: [qsTranslate("App", "Image Files (*.png *.jpg *.jpeg *.webp *.tiff *.bmp)"), qsTranslate("App", "All Files (*.*)")]onAccepted: {if (appBridge && selectedFile) {appBridge.selectCustomMask(selectedFile.toString())diff --git a/src/desktop/qml/components/DenoisingControls.qml b/src/desktop/qml/components/DenoisingControls.qmldeleted file mode 100644index 949ef0e..0000000--- a/src/desktop/qml/components/DenoisingControls.qml+++ /dev/null@@ -1,37 +0,0 @@-import QtQuick-import "../controls"--Column {- id: root- property var appBridge: null- readonly property bool isImage: appBridge ? appBridge.nrMode === "Image" : true- width: parent ? parent.width : 320- spacing: 12-- AppSlider {- objectName: "denoising-strength"- width: parent.width- label: "Noise Reduction"- from: 0; to: 100; stepSize: 1; precision: 0; defaultValue: 50; unit: "%"- value: root.appBridge ? root.appBridge.denoiseStrength : 50- onValueModified: v => { if (root.appBridge) root.appBridge.denoiseStrength = Math.round(v) }- }-- AppCheckBox {- objectName: "denoising-deblock"- label: "Compression Artifact Cleanup"- checked: root.appBridge ? root.appBridge.denoiseDeblock : true- onToggled: v => { if (root.appBridge) root.appBridge.denoiseDeblock = v }- }-- AppSlider {- objectName: "denoising-temporal"- visible: !root.isImage- width: parent.width- label: "Temporal Noise Reduction"- from: 0; to: 100; stepSize: 1; precision: 0; defaultValue: 30; unit: "%"- value: root.appBridge ? root.appBridge.denoiseTemporal : 30- onValueModified: v => { if (root.appBridge) root.appBridge.denoiseTemporal = Math.round(v) }- }--}diff --git a/src/desktop/qml/components/DlssSuperResolutionControls.qml b/src/desktop/qml/components/DlssSuperResolutionControls.qmlindex de539da..68ba3b3 100644--- a/src/desktop/qml/components/DlssSuperResolutionControls.qml+++ b/src/desktop/qml/components/DlssSuperResolutionControls.qml@@ -11,7 +11,7 @@ Column {AppComboBox {width: parent.width- label: "DLSS Mode"+ label: qsTranslate("App", "DLSS Mode")model: appBridge ? appBridge.dlssModeChoices : []currentValue: root.isImage ? (appBridge ? appBridge.upscaleImageDlssMode : "Quality"): (appBridge ? appBridge.upscaleDlssMode : "Quality")@@ -27,7 +27,7 @@ Column {AppComboBox {width: parent.width- label: "DLSS Preset"+ label: qsTranslate("App", "DLSS Preset")model: appBridge ? appBridge.dlssPresetChoices : []currentValue: root.isImage ? (appBridge ? appBridge.upscaleImageDlssPreset : "Default"): (appBridge ? appBridge.upscaleDlssPreset : "Default")diff --git a/src/desktop/qml/components/DropZone.qml b/src/desktop/qml/components/DropZone.qmlindex 532abea..3f91498 100644--- a/src/desktop/qml/components/DropZone.qml+++ b/src/desktop/qml/components/DropZone.qml@@ -8,15 +8,19 @@ Rectangle {property var appBridge: nullproperty string mediaKind: "image/video" // "image", "video", "image/video"+ property bool emptyState: true- // No box visuals: transparent background, no border. The whole empty- // viewport stays clickable (opens file picker) and droppable.- color: dropArea.containsDrag ? Theme.bgSelected : "transparent"+ // The drop target stays over a loaded preview; only the empty-state+ // picker and prompt disappear after an input has been selected.+ color: dropArea.containsDrag ? (emptyState ? Theme.bgSelected : "#220387C2") : "transparent"+ border.color: !emptyState && dropArea.containsDrag ? Theme.accent : "transparent"+ border.width: 1Behavior on color { ColorAnimation { duration: Theme.animFast } }DropArea {id: dropArea+ objectName: "mediaDropArea"anchors.fill: parentonDropped: (drop) => {if (drop.hasUrls && appBridge) {@@ -32,6 +36,7 @@ Rectangle {MouseArea {id: clickAreaanchors.fill: parent+ visible: root.emptyStatehoverEnabled: truecursorShape: Qt.PointingHandCursoronClicked: fileDialog.open()@@ -39,6 +44,7 @@ Rectangle {Column {anchors.centerIn: parent+ visible: root.emptyStatespacing: 16width: Math.min(parent.width - 40, 480)@@ -52,7 +58,7 @@ Rectangle {// Main promptText {anchors.horizontalCenter: parent.horizontalCenter- text: "Drag and drop media files here"+ text: qsTranslate("App", "Drag and drop media files here")font.family: Theme.fontFamilyfont.pixelSize: Theme.fontSizeTitlefont.weight: Font.DemiBold@@ -65,14 +71,14 @@ Rectangle {spacing: 12AppButton {- text: "Choose Files..."+ text: qsTranslate("App", "Choose Files...")iconName: "add_file"variant: "secondary"onClicked: fileDialog.open()}AppButton {- text: "Choose Folder..."+ text: qsTranslate("App", "Choose Folder...")iconName: "add_folder"variant: "secondary"onClicked: folderDialog.open()@@ -82,13 +88,13 @@ Rectangle {FileDialog {id: fileDialog- title: "Select Input Media"+ title: qsTranslate("App", "Select Input Media")fileMode: FileDialog.OpenFilesnameFilters: [- "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 (*.*)"+ qsTranslate("App", "All Media Files (*.mp4 *.mkv *.mov *.avi *.webm *.png *.jpg *.jpeg *.webp *.avif *.tiff *.bmp *.cr2 *.nef *.arw *.dng *.heic)"),+ qsTranslate("App", "Video Files (*.mp4 *.mkv *.mov *.avi *.webm)"),+ qsTranslate("App", "Image Files (*.png *.jpg *.jpeg *.webp *.avif *.tiff *.bmp *.cr2 *.nef *.arw *.dng *.heic)"),+ qsTranslate("App", "All Files (*.*)")]onAccepted: {if (appBridge && selectedFiles.length > 0) {@@ -103,7 +109,7 @@ Rectangle {FolderDialog {id: folderDialog- title: "Select Folder Containing Media"+ title: qsTranslate("App", "Select Folder Containing Media")onAccepted: {if (appBridge) {var folderPath = selectedFolder.toString()diff --git a/src/desktop/qml/components/ExportDialog.qml b/src/desktop/qml/components/ExportDialog.qmlindex 9ad59a2..231629d 100644--- a/src/desktop/qml/components/ExportDialog.qml+++ b/src/desktop/qml/components/ExportDialog.qml@@ -54,7 +54,7 @@ QQC2.Dialog {bottomPadding: 20header: QQC2.Label {- text: "Export"+ text: qsTranslate("App", "Export")color: Theme.textPrimaryfont.family: Theme.fontFamilyfont.pixelSize: Theme.fontSizeTitle@@ -72,11 +72,11 @@ QQC2.Dialog {AppSegmentedControl {width: parent.width- label: "Export Path"+ label: qsTranslate("App", "Export Path")model: [- { label: "Same as Input", value: "input" },- { label: "Output", value: "output" },- { label: "Select Folder", value: "folder" }+ { label: qsTranslate("App", "Same as Input"), value: "input" },+ { label: qsTranslate("App", "Output"), value: "output" },+ { label: qsTranslate("App", "Select Folder"), value: "folder" }]currentValue: exportDialog.destinationModeonActivated: (value) => { exportDialog.destinationMode = value; exportDialog.errorMessage = "" }@@ -86,10 +86,10 @@ QQC2.Dialog {width: parent.widthwrapMode: Text.WordWraptext: exportDialog.destinationMode === "input"- ? "Save each result beside its source file."+ ? qsTranslate("App", "Save each result beside its source file."): (exportDialog.destinationMode === "output"- ? "Save results in the program's outputs folder."- : "Choose the folder where results will be saved.")+ ? qsTranslate("App", "Save results in the program's outputs folder.")+ : qsTranslate("App", "Choose the folder where results will be saved."))font.family: Theme.fontFamilyfont.pixelSize: Theme.fontSizeLabelcolor: Theme.textSecondary@@ -100,7 +100,7 @@ QQC2.Dialog {spacing: 6visible: exportDialog.destinationMode === "folder"AppButton {- text: "Choose Folder..."+ text: qsTranslate("App", "Choose Folder...")iconName: "browse_folder"onClicked: folderDialog.open()}@@ -108,7 +108,7 @@ QQC2.Dialog {width: parent.widthtext: exportDialog.selectedFolder? decodeURIComponent(exportDialog.selectedFolder.replace(/^file:\/\/\//, ""))- : "No folder selected"+ : qsTranslate("App", "No folder selected")elide: Text.ElideMiddlefont.family: Theme.fontFamilyfont.pixelSize: Theme.fontSizeLabel@@ -118,7 +118,7 @@ QQC2.Dialog {AppSegmentedControl {width: parent.width- label: "Rename Mode"+ label: qsTranslate("App", "Rename Mode")model: exportDialog.appBridge ? exportDialog.appBridge.renameModeChoices : []currentValue: exportDialog.renameModeonActivated: (value) => { exportDialog.renameMode = value; exportDialog.errorMessage = "" }@@ -127,7 +127,7 @@ QQC2.Dialog {AppTextField {visible: exportDialog.renameMode === "Custom"width: parent.width- label: "Custom Suffix"+ label: qsTranslate("App", "Custom Suffix")text: exportDialog.customSuffixonTextEdited: (value) => { exportDialog.customSuffix = value; exportDialog.errorMessage = "" }}@@ -146,12 +146,12 @@ QQC2.Dialog {width: parent.widthspacing: 8AppButton {- text: "Cancel"+ text: qsTranslate("App", "Cancel")width: (parent.width - 8) / 2onClicked: exportDialog.close()}AppButton {- text: "Export / Start"+ text: qsTranslate("App", "Export / Start")iconName: "start_render"variant: "primary"width: (parent.width - 8) / 2@@ -172,7 +172,7 @@ QQC2.Dialog {FolderDialog {id: folderDialog- title: "Select Export Folder"+ title: qsTranslate("App", "Select Export Folder")onAccepted: {exportDialog.selectedFolder = selectedFolder.toString()exportDialog.errorMessage = ""diff --git a/src/desktop/qml/components/ExportSettingsControls.qml b/src/desktop/qml/components/ExportSettingsControls.qmlindex 0e2e4fe..653f541 100644--- a/src/desktop/qml/components/ExportSettingsControls.qml+++ b/src/desktop/qml/components/ExportSettingsControls.qml@@ -15,7 +15,7 @@ Column {spacing: 12AppComboBox {width: parent.width- label: "Output Format"+ label: qsTranslate("App", "Output Format")model: appBridge ? appBridge.imageFormatChoices : []currentValue: appBridge ? appBridge.imageFormat : "PNG"onActivated: v => {@@ -26,7 +26,7 @@ Column {AppComboBox {objectName: "imageBitDepthSelector"width: parent.width- label: "Bit Depth"+ label: qsTranslate("App", "Bit Depth")model: appBridge && ["PNG", "TIFF"].indexOf(appBridge.imageFormat) >= 0? [{label: "8 Bit", value: 8}, {label: "16 Bit", value: 16}]: [{label: "8 Bit", value: 8}]@@ -39,7 +39,7 @@ Column {AppSlider {visible: appBridge && ["JPEG", "WebP", "AVIF"].indexOf(appBridge.imageFormat) >= 0width: parent.width- label: "Image Quality"+ label: qsTranslate("App", "Image Quality")from: 1to: 100stepSize: 1@@ -59,7 +59,7 @@ Column {spacing: 12AppComboBox {width: parent.width- label: "Video Codec"+ label: qsTranslate("App", "Video Codec")model: appBridge ? appBridge.codecChoices : []currentValue: appBridge ? appBridge.videoCodec : "H.264 (NVIDIA NVENC)"onActivated: v => {@@ -68,15 +68,20 @@ Column {}}AppComboBox {+ objectName: "videoContainerSelector"width: parent.width- label: "Container (automatic)"+ label: qsTranslate("App", "Container")model: appBridge ? appBridge.containerChoices : []currentValue: appBridge ? appBridge.videoContainer : "MP4"- enabled: false+ enabled: !!appBridge+ onActivated: v => {+ if (appBridge)+ appBridge.videoContainer = v;+ }}AppComboBox {width: parent.width- label: "Encoding Quality"+ label: qsTranslate("App", "Encoding Quality")visible: !appBridge || appBridge.fixedQualityCodecs.indexOf(appBridge.videoCodec) < 0model: appBridge ? appBridge.encodingQualityChoices : []currentValue: appBridge ? appBridge.videoQuality : "Auto (Default)"@@ -87,12 +92,12 @@ Column {}Text {visible: appBridge && appBridge.fixedQualityCodecs.indexOf(appBridge.videoCodec) >= 0- text: "Encoding Quality: Fixed by codec"+ text: qsTranslate("App", "Encoding Quality: Fixed by codec")color: Theme.textSecondaryfont.pixelSize: Theme.fontSizeSmall}AppCheckBox {- label: "Preserve / Export 10-bit HDR"+ label: qsTranslate("App", "Preserve / Export 10-bit HDR")checked: appBridge ? appBridge.videoHdrMode : falseenabled: appBridge ? appBridge.videoHdrSupported : falseonToggled: v => {diff --git a/src/desktop/qml/components/FrameGenerationControls.qml b/src/desktop/qml/components/FrameGenerationControls.qmlindex 84bba59..e1f6424 100644--- a/src/desktop/qml/components/FrameGenerationControls.qml+++ b/src/desktop/qml/components/FrameGenerationControls.qml@@ -1,42 +1,42 @@-import QtQuick-import QtQuick.Dialogs-import ".."-import "../controls"--Column {- id: root- property var appBridge: null- readonly property bool isImage: appBridge ? appBridge.nrMode === "Image" : true- width: parent ? parent.width : 320- 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- }-}+import QtQuick+import QtQuick.Dialogs+import ".."+import "../controls"++Column {+ id: root+ property var appBridge: null+ readonly property bool isImage: appBridge ? appBridge.nrMode === "Image" : true+ width: parent ? parent.width : 320+ spacing: 12+ AppComboBox {+ width: parent.width+ label: qsTranslate("App", "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: qsTranslate("App", "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+ }+}diff --git a/src/desktop/qml/components/HeaderBar.qml b/src/desktop/qml/components/HeaderBar.qmlindex 76e21b9..856d50a 100644--- a/src/desktop/qml/components/HeaderBar.qml+++ b/src/desktop/qml/components/HeaderBar.qml@@ -5,6 +5,9 @@ import "../controls"Rectangle {id: root+ // Native window buttons retain their Windows positions in RTL locales.+ LayoutMirroring.enabled: false+ LayoutMirroring.childrenInherit: trueproperty var appBridge: nullproperty var windowRef: nullreadonly property bool compact: width < 1320@@ -126,10 +129,10 @@ Rectangle {anchors.verticalCenter: parent.verticalCenterspacing: 4readonly property var tabs: [- { id:"neural-rendering", full:"Neural Rendering", short:"Neural", icon:"neural_rendering" },- { id:"live", full:"Live", short:"Live", icon:"live_video" },- { id:"settings", full:"Settings", short:"Settings", icon:"settings" },- { id:"help", full:"Help", short:"Help", icon:"help" }+ { id:"neural-rendering", full:qsTranslate("App", "Neural Rendering"), short:qsTranslate("App", "Neural"), icon:"neural_rendering" },+ { id:"live", full:qsTranslate("App", "Live"), short:qsTranslate("App", "Live"), icon:"live_video" },+ { id:"settings", full:qsTranslate("App", "Settings"), short:qsTranslate("App", "Settings"), icon:"settings" },+ { id:"help", full:qsTranslate("App", "Help"), short:qsTranslate("App", "Help"), icon:"help" }]Repeater {model: navTabs.tabsdiff --git a/src/desktop/qml/components/MediaViewport.qml b/src/desktop/qml/components/MediaViewport.qmlindex 2ec8fb2..053136f 100644--- a/src/desktop/qml/components/MediaViewport.qml+++ b/src/desktop/qml/components/MediaViewport.qml@@ -2,11 +2,16 @@ import QtQuickimport QtQuick.Windowimport QtQuick.Controls as QQC2import QtMultimedia+import VisualEnhancer 1.0+import "PlaybackVolume.js" as PlaybackVolumeimport ".."import "../controls"Rectangle {id: viewport+ // Media comparisons and transport coordinates keep a left-to-right axis.+ LayoutMirroring.enabled: false+ LayoutMirroring.childrenInherit: trueobjectName: "mediaViewport"property var appBridge: nullproperty string viewMode: "split"@@ -112,6 +117,15 @@ Rectangle {readonly property real fitHeight: Math.max(1, twoUpLayout && !isVideo ? canvas.height - 8 : canvas.height)readonly property real fitScale: Math.max(0.0001, Math.min(fitWidth / sourceWidth, fitHeight / sourceHeight))readonly property real displayScale: fitScale * zoomFactor+ readonly property bool decodedOutputIsProcessed: !hasRangePlayback || Boolean(fiPinned && fiPinned.url)+ // Stills report rendered size through the bridge; video clips expose+ // their decoded dimensions on the output surface once loaded.+ readonly property int displayedOutputWidth: appBridge && appBridge.previewOutputIsVideo+ ? (decodedOutputIsProcessed ? Math.round(outputSurface.sourceRect.width) : 0)+ : (appBridge ? appBridge.outputWidth : 0)+ readonly property int displayedOutputHeight: appBridge && appBridge.previewOutputIsVideo+ ? (decodedOutputIsProcessed ? Math.round(outputSurface.sourceRect.height) : 0)+ : (appBridge ? appBridge.outputHeight : 0)function resetPan() { panX = 0; panY = 0 }function fitToWindow() { zoomFactor = 1.0; resetPan() }@@ -148,7 +162,7 @@ Rectangle {// 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 }+ AudioOutput { id: mediaAudio; objectName: "previewAudioOutput"; volume: PlaybackVolume.gainForLevel(80); muted: false }// Dedicated input player: transport/scrubbing always survives a preview.MediaPlayer {id: inputPlayer@@ -172,7 +186,7 @@ Rectangle {onMediaStatusChanged: (status) => {if ((status === MediaPlayer.LoadedMedia || status === MediaPlayer.BufferedMedia) && primePending) {primePending = false- // Play-then-pause forces WMF to paint the first frame; a bare+ // Play-then-pause primes the decoder's first frame; a bare// pause()/position=0 leaves VideoOutput black on Windows.play()pause()@@ -312,25 +326,19 @@ Rectangle {// hidden, snapped exact on pause/seek); everywhere else it is the// latest preview output. Range clips play once (loops: 1) so a span// never replays at its end — playback continues with the original.- MediaPlayer {+ PreviewPlayer {id: outputPlayerobjectName: "outputPlayer"source: viewport.isVideo && appBridge ? (viewport.hasRangePlayback ? viewport.fiOutputUrl : (appBridge.previewOutputIsVideo ? appBridge.previewOutputUrl : "")) : ""- audioOutput: mediaAudiovideoOutput: outputSurfaceloops: viewport.hasRangePlayback ? 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.LoadedMedia) {+ var span = viewport.hasRangePlayback ? viewport.fiPinned : null+ var base = viewport.playheadMs - (span && span.start !== undefined ? span.start * 1000 : 0)+ if (Math.abs(position - base) > 20)+ position = Math.max(0, Math.min(duration - 1, base))+ if (inputPlayer.playbackState === MediaPlayer.PlayingState) play()}if (status === MediaPlayer.InvalidMedia && viewport.showingOutput) {viewport.playerError = errorString !== "" ? errorString : "Preview output is not playable."@@ -371,23 +379,31 @@ Rectangle {id: toolbarz: 20anchors.top: parent.top; anchors.left: parent.left; anchors.right: parent.right- height: 42; visible: viewport.hasInput+ // Reserve room for the selector and both FPS values before a clip+ // loads, so metadata arriving cannot move the preview canvas.+ readonly property bool stacked: width < 10 + Math.max(viewSelectors.implicitWidth, viewport.isVideo ? 225 : 250)+ + 12 + Math.max(mediaFacts.implicitWidth, viewport.isVideo ? 320 : 230)+ + (zoomTools.visible ? 12 + zoomTools.implicitWidth : 0) + 10+ height: stacked ? 58 : 42; visible: viewport.hasInputcolor: "#E014171D"; border.color: Theme.borderSubtleRow {- anchors.left: parent.left; anchors.leftMargin: 10; anchors.verticalCenter: parent.verticalCenter; spacing: 8+ id: viewSelectors+ anchors.left: parent.left; anchors.leftMargin: 10+ anchors.verticalCenter: parent.verticalCenter+ anchors.verticalCenterOffset: toolbar.stacked ? -12 : 0AppSegmentedControl {objectName: "imageComparisonSelector"visible: !viewport.isVideowidth: 250- model: [{label:"Split",value:"split"},{label:"2-Up",value:"sideBySide"},{label:"Output",value:"single"}]+ model: [{label:qsTranslate("App", "Split"),value:"split"},{label:qsTranslate("App", "2-Up"),value:"sideBySide"},{label:qsTranslate("App", "Output"),value:"single"}]currentValue: viewport.viewModeonActivated: (v) => { viewport.viewMode = v; viewport.forceActiveFocus() }}AppSegmentedControl {visible: viewport.isVideo && (viewport.hasOutput || viewport.videoTwoUp)width: 225- model: [{label:"Input",value:"input"},{label:"Output",value:"output"},{label:"2-Up",value:"twoup"}]+ model: [{label:qsTranslate("App", "Input"),value:"input"},{label:qsTranslate("App", "Output"),value:"output"},{label:qsTranslate("App", "2-Up"),value:"twoup"}]currentValue: viewport.videoTwoUp ? "twoup" : (viewport.showVideoOutput ? "output" : "input")onActivated: (v) => {if (v === "twoup") {@@ -398,32 +414,103 @@ Rectangle {}}}+ }++ Row {+ id: mediaFacts+ objectName: "mediaInfoStrip"+ anchors.left: toolbar.stacked ? parent.left : viewSelectors.right+ anchors.leftMargin: toolbar.stacked ? 10 : 12+ anchors.right: toolbar.stacked ? parent.right : (zoomTools.visible ? zoomTools.left : parent.right)+ anchors.rightMargin: toolbar.stacked ? 10 : (zoomTools.visible ? 12 : 10)+ anchors.verticalCenter: parent.verticalCenter+ anchors.verticalCenterOffset: toolbar.stacked ? 14 : 0+ spacing: 9+ clip: true++ Text {+ id: inputInfoLabel+ text: qsTranslate("App", "Input")+ color: Theme.textMuted+ font.family: Theme.fontFamily; font.pixelSize: Theme.fontSizeSmall+ }+ Text {+ objectName: "inputResolutionText"+ text: appBridge && appBridge.sourceWidth > 0 && appBridge.sourceHeight > 0+ ? appBridge.sourceWidth + "×" + appBridge.sourceHeight : "—"+ color: Theme.textPrimary+ font.family: Theme.monoFontFamily; font.pixelSize: Theme.fontSizeSmall+ anchors.baseline: inputInfoLabel.baseline+ }Text {- width: Math.max(120, toolbar.width - 620)- text: appBridge ? appBridge.inputInfoText + (appBridge.hasOutputPreview ? " -> " + appBridge.outputInfoText : "") : ""- elide: Text.ElideMiddle; color: Theme.textSecondary+ objectName: "inputFpsText"+ visible: viewport.isVideo && appBridge && appBridge.sourceFps > 0+ text: appBridge ? (Math.round(appBridge.sourceFps * 1000) / 1000) + " FPS" : ""+ color: Theme.textSecondaryfont.family: Theme.monoFontFamily; font.pixelSize: Theme.fontSizeSmall+ anchors.baseline: inputInfoLabel.baseline+ }+ Rectangle {+ visible: viewport.hasOutput+ width: 1; height: 13; color: Theme.borderDefaultanchors.verticalCenter: parent.verticalCenter}+ Text {+ visible: viewport.hasOutput+ text: qsTranslate("App", "Output")+ color: Theme.textMuted+ font.family: Theme.fontFamily; font.pixelSize: Theme.fontSizeSmall+ anchors.baseline: inputInfoLabel.baseline+ }+ Text {+ objectName: "outputResolutionText"+ visible: viewport.hasOutput+ text: viewport.displayedOutputWidth > 0 && viewport.displayedOutputHeight > 0+ ? viewport.displayedOutputWidth + "×" + viewport.displayedOutputHeight : "—"+ color: Theme.textAccent+ font.family: Theme.monoFontFamily; font.pixelSize: Theme.fontSizeSmall+ anchors.baseline: inputInfoLabel.baseline+ }+ Text {+ objectName: "outputFpsText"+ visible: viewport.isVideo && viewport.hasOutput && appBridge+ && appBridge.previewOutputIsVideo+ text: (viewport.decodedOutputIsProcessed && outputPlayer.videoFps > 0+ ? Math.round(outputPlayer.videoFps * 1000) / 1000 : "—")+ + " FPS"+ color: Theme.textSecondary+ font.family: Theme.monoFontFamily; font.pixelSize: Theme.fontSizeSmall+ anchors.baseline: inputInfoLabel.baseline+ }}Row {+ id: zoomToolsvisible: !viewport.isVideo || viewport.showingTwoUp- anchors.right: parent.right; anchors.rightMargin: 10; anchors.verticalCenter: parent.verticalCenter; spacing: 6- AppIconButton { iconName: "fit_to_window"; buttonSize: 26; tooltipText: "Fit to window"; onClicked: viewport.fitToWindow() }- AppIconButton { iconName: "actual_size"; buttonSize: 26; tooltipText: "Actual pixels"; onClicked: viewport.actualPixels() }+ anchors.right: parent.right; anchors.rightMargin: 10+ anchors.verticalCenter: parent.verticalCenter+ anchors.verticalCenterOffset: toolbar.stacked ? -12 : 0+ spacing: 6+ AppIconButton { iconName: "fit_to_window"; buttonSize: 26; tooltipText: qsTranslate("App", "Fit to window"); onClicked: viewport.fitToWindow() }+ AppIconButton { iconName: "actual_size"; buttonSize: 26; tooltipText: qsTranslate("App", "Actual pixels"); 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 { objectName: "previewZoomOut"; iconName: "zoom_out"; tooltipText: "Zoom out"; onClicked: viewport.changeZoom(0.8) }- AppIconButton { objectName: "previewZoomIn"; iconName: "zoom_in"; tooltipText: "Zoom in"; onClicked: viewport.changeZoom(1.25) }+ AppIconButton { objectName: "previewZoomOut"; iconName: "zoom_out"; tooltipText: qsTranslate("App", "Zoom out"); onClicked: viewport.changeZoom(0.8) }+ AppIconButton { objectName: "previewZoomIn"; iconName: "zoom_in"; tooltipText: qsTranslate("App", "Zoom in"); onClicked: viewport.changeZoom(1.25) }AppIconButton {iconName: appBridge && appBridge.focusPreview ? "exit_fullscreen" : "focus_preview"- tooltipText: appBridge && appBridge.focusPreview ? "Exit focus preview" : "Focus preview"+ tooltipText: appBridge && appBridge.focusPreview ? qsTranslate("App", "Exit focus preview") : qsTranslate("App", "Focus preview")onClicked: { if (appBridge) appBridge.focusPreview = !appBridge.focusPreview }}}}- DropZone { anchors.fill: parent; visible: !viewport.hasInput; appBridge: viewport.appBridge }+ DropZone {+ objectName: "mediaDropZone"+ anchors.fill: parent+ z: 30+ appBridge: viewport.appBridge+ emptyState: !viewport.hasInput+ }Item {id: canvas@@ -432,7 +519,7 @@ Rectangle {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.+ // visible first frame while the player 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).@@ -472,6 +559,17 @@ Rectangle {width: viewport.showingTwoUp ? viewport.comparisonPaneWidth : parent.widthvisible: viewport.isVideo && (viewport.showingOutput || viewport.showingTwoUp)clip: true+ readonly property rect stillFrameRect: {+ var w = appBridge && appBridge.outputWidth > 0 ? appBridge.outputWidth : viewport.sourceWidth+ var h = appBridge && appBridge.outputHeight > 0 ? appBridge.outputHeight : viewport.sourceHeight+ // Reuse the player's exact fitted rectangle for matching+ // aspect ratios, including scaled previews and video SAR.+ if (w * viewport.sourceHeight === h * viewport.sourceWidth+ && inputSurface.sourceRect.width > 0 && inputSurface.sourceRect.height > 0)+ return inputSurface.contentRect+ var fit = Math.min(width / w, height / h)+ return Qt.rect((width - w * fit) / 2, (height - h * fit) / 2, w * fit, h * fit)+ }VideoOutput {id: outputSurfaceobjectName: "outputSurface"@@ -487,12 +585,15 @@ Rectangle {objectName: "outputStillFrame"visible: viewport.hasStillVideoOutputsource: visible && appBridge ? appBridge.previewOutputUrl : ""- width: parent.width; height: parent.height+ width: parent.stillFrameRect.width; height: parent.stillFrameRect.heighttransformOrigin: Item.TopLeftscale: viewport.showingTwoUp ? viewport.zoomFactor : 1.0- x: (parent.width - width * scale) / 2 + (viewport.showingTwoUp ? viewport.panX : 0)- y: (parent.height - height * scale) / 2 + (viewport.showingTwoUp ? viewport.panY : 0)- fillMode: Image.PreserveAspectFit; cache: false; smooth: true+ x: (parent.width - parent.width * scale) / 2 + parent.stillFrameRect.x * scale + (viewport.showingTwoUp ? viewport.panX : 0)+ y: (parent.height - parent.height * scale) / 2 + parent.stillFrameRect.y * scale + (viewport.showingTwoUp ? viewport.panY : 0)+ // AspectFit rounds its internal letterbox offset. Stretch an+ // already fitted item so its fractional position is retained,+ // matching VideoOutput instead of jumping on an Input/Output swap.+ fillMode: Image.Stretch; cache: false; smooth: true}}@@ -500,19 +601,19 @@ Rectangle {// Mirrors the image side-by-side pattern.AppBadge {anchors.left: parent.left; anchors.top: parent.top; anchors.margins: 10- visible: viewport.showingTwoUp; text: "INPUT"+ visible: viewport.showingTwoUp; text: qsTranslate("App", "INPUT")}AppBadge {anchors.right: parent.right; anchors.top: parent.top; anchors.margins: 10visible: viewport.showingTwoUp- text: viewport.outputReady ? ("OUTPUT" + (appBridge && appBridge.previewSourceFrame > 0 ? " f" + appBridge.previewSourceFrame : "")) : "NO OUTPUT"+ text: viewport.outputReady ? (qsTranslate("App", "OUTPUT") + (appBridge && appBridge.previewSourceFrame > 0 ? qsTranslate("App", " f") + appBridge.previewSourceFrame : "")) : qsTranslate("App", "NO OUTPUT")variant: viewport.outputReady ? "accent" : "neutral"}Text {anchors.right: parent.right; anchors.verticalCenter: parent.verticalCenterwidth: (parent.width - 4) / 2; horizontalAlignment: Text.AlignHCentervisible: viewport.showingTwoUp && !viewport.outputReady- text: "Loading preview..."+ text: qsTranslate("App", "Loading preview...")color: Theme.textMuted; font.family: Theme.fontFamily; font.pixelSize: Theme.fontSizeSmall}@@ -526,7 +627,7 @@ Rectangle {color: "#AA0B0D12"Text {anchors.centerIn: parent- text: "Loading preview..."+ text: qsTranslate("App", "Loading preview...")color: Theme.textMuted; font.family: Theme.fontFamily; font.pixelSize: Theme.fontSizeSmall}}@@ -536,12 +637,14 @@ Rectangle {// Frozen (both players paused) for frame-accurate A/B comparison.MouseArea {id: peekArea+ objectName: "videoPeekArea"anchors.fill: parentz: 4visible: viewport.isVideo && viewport.hasOutput && !viewport.showingTwoUp+ enabled: viewport.outputReady && appBridge && !appBridge.previewBusyacceptedButtons: Qt.LeftButtonhoverEnabled: true- cursorShape: containsMouse ? Qt.PointingHandCursor : Qt.ArrowCursor+ cursorShape: enabled && containsMouse ? Qt.PointingHandCursor : Qt.ArrowCursoronPressed: (mouse) => {viewport.peekPrevShowOutput = viewport.showVideoOutputviewport.peekWasPlaying = viewport.activePlayer && viewport.activePlayer.playbackState === MediaPlayer.PlayingState@@ -560,6 +663,7 @@ Rectangle {viewport.activePlayer.play()viewport.peekWasPlaying = false}+ onEnabledChanged: { if (!enabled) endPeek(true) }onReleased: endPeek(true)onCanceled: endPeek(true)}@@ -575,7 +679,7 @@ Rectangle {Text {id: peekLabelanchors.centerIn: parent- text: "PREVIEW"+ text: qsTranslate("App", "PREVIEW")color: "white"; font.family: Theme.fontFamily; font.pixelSize: Theme.fontSizeSmall; font.bold: true}}@@ -593,7 +697,7 @@ Rectangle {Text {anchors.centerIn: parent; width: parent.width - 40horizontalAlignment: Text.AlignHCenter; wrapMode: Text.Wrap- text: "Video cannot be played natively:\n" + viewport.playerError + "\nPoster frame shown. Scrub with < > or open the file externally."+ text: qsTranslate("App", "Video cannot be played natively:\n") + viewport.playerError + qsTranslate("App", "\nPoster frame shown. Scrub with < > or open the file externally.")color: Theme.warning; font.family: Theme.fontFamily; font.pixelSize: Theme.fontSizeSmall}}@@ -694,7 +798,7 @@ Rectangle {y: 4 + (parent.height - 8 - height * scale) / 2 + viewport.panYsource: appBridge ? appBridge.previewInputUrl : ""; fillMode: Image.PreserveAspectFit; cache: false}- AppBadge { anchors.left: parent.left; anchors.top: parent.top; anchors.margins: 10; text: "INPUT" }+ AppBadge { anchors.left: parent.left; anchors.top: parent.top; anchors.margins: 10; text: qsTranslate("App", "INPUT") }}Rectangle {width: (parent.width - 4) / 2; height: parent.height; color: Theme.bgBase@@ -707,7 +811,7 @@ Rectangle {y: 4 + (parent.height - 8 - height * scale) / 2 + viewport.panYsource: 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" }+ AppBadge { anchors.left: parent.left; anchors.top: parent.top; anchors.margins: 10; text: viewport.hasOutput ? qsTranslate("App", "OUTPUT") : qsTranslate("App", "NO OUTPUT"); variant: viewport.hasOutput ? "accent" : "neutral" }}}@@ -765,6 +869,7 @@ Rectangle {// tab); the output pane mirrors it. Scrubbing anywhere addresses// input frames, so refreshes can never clobber the preview.player: inputPlayer+ audioOutput: mediaAudioframeRate: viewport.inputFpsfallbackDurationMs: viewport.inputDurationMsfallbackFrameRate: viewport.inputFps@@ -776,31 +881,41 @@ Rectangle {}}- // Status readout, bottom-left. Idle "Ready." is hidden when empty;- // any other status still shows, and everything shows once loaded.- Row {+ // A single status light; completion briefly acknowledges readiness.+ Rectangle {id: statusOverlay+ objectName: "previewStatusIndicator"z: 30- visible: viewport.hasInput || (appBridge && appBridge.statusMessage !== "Ready.")+ readonly property string statusKind: {+ if (!appBridge) return ""+ if (appBridge.runtimeState === "Failed") return "error"+ if (appBridge.previewBusy || appBridge.isProcessing+ || appBridge.runtimeState === "Initializing"+ || appBridge.operationState === "LiveRunning") return "processing"+ if (appBridge.previewError !== "" || inputPlayer.mediaStatus === MediaPlayer.InvalidMedia+ || (appBridge.previewOutputIsVideo && outputPlayer.mediaStatus === MediaPlayer.InvalidMedia)) return "error"+ return viewport.hasInput ? "ready" : ""+ }+ property bool readyExpired: false+ function updateIndicator() {+ readyHideTimer.stop()+ readyExpired = false+ if (statusKind === "ready") readyHideTimer.restart()+ }+ onStatusKindChanged: updateIndicator()+ Component.onCompleted: updateIndicator()+ visible: statusKind !== "" && (statusKind !== "ready" || !readyExpired)+ width: 8; height: 8; radius: 4+ color: statusKind === "error" ? Theme.danger : (statusKind === "processing" ? Theme.accent : Theme.success)anchors.left: parent.left; anchors.leftMargin: 10anchors.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+ anchors.bottomMargin: 10+ Accessible.name: appBridge ? appBridge.statusMessage : ""+ Timer {+ id: readyHideTimer+ objectName: "previewReadyHideTimer"+ interval: 3000; repeat: false+ onTriggered: statusOverlay.readyExpired = true}}@@ -823,7 +938,7 @@ Rectangle {id: previewFontMetricsfont.family: Theme.fontFamilyfont.pixelSize: Theme.fontSizeBody- text: "Show in Explorer"+ text: qsTranslate("App", "Show in Explorer")}background: Rectangle {@@ -868,21 +983,21 @@ Rectangle {QQC2.MenuItem {implicitHeight: 25- text: viewport.isVideo ? "Clear video" : "Clear image"+ text: viewport.isVideo ? qsTranslate("App", "Clear video") : qsTranslate("App", "Clear image")icon.name: "trash"enabled: viewport.hasInput && appBridge && appBridge.canModifyQueueonTriggered: { if (appBridge) appBridge.clearSelectedPreviewItem() }}QQC2.MenuItem {implicitHeight: 25- text: "Clear all"+ text: qsTranslate("App", "Clear all")icon.name: "clear_all"enabled: viewport.hasInput && appBridge && appBridge.canModifyQueueonTriggered: { if (appBridge) appBridge.clearActiveQueue() }}QQC2.MenuItem {implicitHeight: 25- text: "Show in Explorer"+ text: qsTranslate("App", "Show in Explorer")icon.name: "reveal_in_explorer"enabled: viewport.hasInput && appBridgeonTriggered: { if (appBridge) appBridge.showSelectedInExplorer() }diff --git a/src/desktop/qml/components/MenuStrip.qml b/src/desktop/qml/components/MenuStrip.qmlindex b323d22..186d848 100644--- a/src/desktop/qml/components/MenuStrip.qml+++ b/src/desktop/qml/components/MenuStrip.qml@@ -79,10 +79,10 @@ Row {// -- menu title buttons -------------------------------------------Repeater {model: [- { label: "File", menu: fileMenu },- { label: "View", menu: viewMenu },- { label: "Process", menu: processMenu },- { label: "Help", menu: helpMenu }+ { label: qsTranslate("App", "File"), menu: fileMenu },+ { label: qsTranslate("App", "View"), menu: viewMenu },+ { label: qsTranslate("App", "Process"), menu: processMenu },+ { label: qsTranslate("App", "Help"), menu: helpMenu }]Item {required property var modelData@@ -118,18 +118,18 @@ Row {delegate: menuDelegateonClosed: root.onMenuClosed(fileMenu)QQC2.MenuItem {- text: "Open Outputs Folder"+ text: qsTranslate("App", "Open Outputs Folder")enabled: root.appBridge !== nullonTriggered: { if (root.appBridge) root.appBridge.openFolder("") }}QQC2.MenuItem {- text: "Open Logs Folder"+ text: qsTranslate("App", "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"+ text: qsTranslate("App", "Exit")onTriggered: root.exitRequested()}}@@ -141,54 +141,54 @@ Row {delegate: menuDelegateonClosed: root.onMenuClosed(viewMenu)QQC2.MenuItem {- text: "Neural Rendering"+ text: qsTranslate("App", "Neural Rendering")checkable: truechecked: root.appBridge && root.appBridge.activeTab === "neural-rendering"onTriggered: { if (root.appBridge) root.appBridge.activeTab = "neural-rendering" }}QQC2.MenuItem {- text: "Upscale"+ text: qsTranslate("App", "Upscale")checkable: truechecked: root.appBridge && root.appBridge.activeTab === "upscale"onTriggered: { if (root.appBridge) root.appBridge.activeTab = "upscale" }}QQC2.MenuItem {- text: "Frame Interpolation"+ text: qsTranslate("App", "Frame Interpolation")checkable: truechecked: root.appBridge && root.appBridge.activeTab === "frame-interpolation"onTriggered: { if (root.appBridge) root.appBridge.activeTab = "frame-interpolation" }}QQC2.MenuItem {- text: "Live"+ text: qsTranslate("App", "Live")checkable: truechecked: root.appBridge && root.appBridge.activeTab === "live"onTriggered: { if (root.appBridge) root.appBridge.activeTab = "live" }}QQC2.MenuItem {- text: "Settings"+ text: qsTranslate("App", "Settings")checkable: truechecked: root.appBridge && root.appBridge.activeTab === "settings"onTriggered: { if (root.appBridge) root.appBridge.activeTab = "settings" }}QQC2.MenuItem {- text: "Help"+ text: qsTranslate("App", "Help")checkable: truechecked: root.appBridge && root.appBridge.activeTab === "help"onTriggered: { if (root.appBridge) root.appBridge.activeTab = "help" }}Loader { sourceComponent: menuSeparator }QQC2.MenuItem {- text: "Focus Preview"+ text: qsTranslate("App", "Focus Preview")checkable: truechecked: root.appBridge ? root.appBridge.focusPreview : falseonTriggered: { if (root.appBridge) root.appBridge.focusPreview = !root.appBridge.focusPreview }}QQC2.MenuItem {- text: "Fullscreen"+ text: qsTranslate("App", "Fullscreen")onTriggered: root.toggleFullscreenRequested()}QQC2.MenuItem {- text: "Console"+ text: qsTranslate("App", "Console")checkable: truechecked: root.consoleOpenonTriggered: root.toggleConsoleRequested()@@ -202,23 +202,23 @@ Row {delegate: menuDelegateonClosed: root.onMenuClosed(processMenu)QQC2.MenuItem {- text: "Start / Render"+ text: qsTranslate("App", "Start / Render")enabled: root.appBridge ? ((root.appBridge.activeTab === "neural-rendering" || root.appBridge.activeTab === "upscale" || root.appBridge.activeTab === "frame-interpolation") && root.appBridge.operationState === "Idle" && root.appBridge.runtimeState === "Ready" && !root.appBridge.isLiveRunning) : falseonTriggered: { if (root.appBridge) root.appBridge.requestActiveBatchExport() }}QQC2.MenuItem {- text: "Preview"+ text: qsTranslate("App", "Preview")enabled: root.appBridge ? root.appBridge.canPreview : falseonTriggered: { if (root.appBridge) root.appBridge.renderPreview() }}QQC2.MenuItem {- text: "Stop"+ text: qsTranslate("App", "Stop")enabled: root.appBridge ? root.appBridge.canStop : falseonTriggered: { if (root.appBridge) root.appBridge.stopActiveBatch() }}Loader { sourceComponent: menuSeparator }QQC2.MenuItem {- text: "Stop Live Session"+ text: qsTranslate("App", "Stop Live Session")enabled: root.appBridge ? root.appBridge.isLiveRunning : falseonTriggered: { if (root.appBridge) root.appBridge.stopLive() }}@@ -231,11 +231,11 @@ Row {delegate: menuDelegateonClosed: root.onMenuClosed(helpMenu)QQC2.MenuItem {- text: "Help"+ text: qsTranslate("App", "Help")onTriggered: { if (root.appBridge) root.appBridge.activeTab = "help" }}QQC2.MenuItem {- text: "Open Logs Folder"+ text: qsTranslate("App", "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/NeuralModelControls.qml b/src/desktop/qml/components/NeuralModelControls.qmlindex ed232ab..9bb0582 100644--- a/src/desktop/qml/components/NeuralModelControls.qml+++ b/src/desktop/qml/components/NeuralModelControls.qml@@ -1,270 +1,270 @@-import QtQuick-import QtQuick.Dialogs-import ".."-import "../controls"--Column {- id: root- property var appBridge: null- readonly property bool isImage: appBridge ? appBridge.nrMode === "Image" : true- width: parent ? parent.width : 320- 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;- }- }-- 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;- }- }-- Text {- width: parent.width- text: "Composition & Masking"- font.family: Theme.fontFamily- font.pixelSize: Theme.fontSizeSubtitle- color: Theme.textSecondary- }- // Detail-Only Preset Button- Row {- width: parent.width- spacing: 8-- AppButton {- text: "Apply Detail-Only Preset"- iconName: "quality_enhance"- 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..."- iconName: "load_mask"- buttonHeight: 24- onClicked: maskDialog.open()- }-- AppButton {- text: "Clear Mask"- iconName: "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());- }- }- }-}+import QtQuick+import QtQuick.Dialogs+import ".."+import "../controls"++Column {+ id: root+ property var appBridge: null+ readonly property bool isImage: appBridge ? appBridge.nrMode === "Image" : true+ width: parent ? parent.width : 320+ spacing: 12+ AppSegmentedControl {+ width: parent.width+ label: qsTranslate("App", "NR Style")+ model: appBridge ? appBridge.nrStyleChoices : []+ currentValue: appBridge ? appBridge.nrStyle : "Default"+ onActivated: v => {+ if (appBridge)+ appBridge.nrStyle = v;+ }+ }++ AppSlider {+ width: parent.width+ label: qsTranslate("App", "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: qsTranslate("App", "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: qsTranslate("App", "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: qsTranslate("App", "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: qsTranslate("App", "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: qsTranslate("App", "Automatic Mask")+ checked: appBridge ? appBridge.automaticMask : false+ onToggled: c => {+ if (appBridge)+ appBridge.automaticMask = c;+ }+ }++ AppSlider {+ visible: !root.isImage+ width: parent.width+ label: qsTranslate("App", "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;+ }+ }++ Text {+ width: parent.width+ text: qsTranslate("App", "Composition & Masking")+ font.family: Theme.fontFamily+ font.pixelSize: Theme.fontSizeSubtitle+ color: Theme.textSecondary+ }+ // Detail-Only Preset Button+ Row {+ width: parent.width+ spacing: 8++ AppButton {+ text: qsTranslate("App", "Apply Detail-Only Preset")+ iconName: "quality_enhance"+ width: parent.width+ buttonHeight: 28+ onClicked: {+ if (appBridge)+ appBridge.applyDetailOnly();+ }+ }+ }++ // Sliders+ AppSlider {+ width: parent.width+ label: qsTranslate("App", "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: qsTranslate("App", "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: qsTranslate("App", "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: qsTranslate("App", "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: qsTranslate("App", "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: qsTranslate("App", "Load Custom Mask...")+ iconName: "load_mask"+ buttonHeight: 24+ onClicked: maskDialog.open()+ }++ AppButton {+ text: qsTranslate("App", "Clear Mask")+ iconName: "clear_mask"+ buttonHeight: 24+ onClicked: {+ if (appBridge)+ appBridge.clearCustomMask();+ }+ }+ }++ Text {+ anchors.horizontalCenter: parent.horizontalCenter+ text: appBridge ? appBridge.customMaskStatus : qsTranslate("App", "No mask loaded")+ font.family: Theme.monoFontFamily+ font.pixelSize: Theme.fontSizeSmall+ color: Theme.textMuted+ }+ }+ }++ FileDialog {+ id: maskDialog+ title: qsTranslate("App", "Select Custom NR Mask")+ nameFilters: [qsTranslate("App", "Image Files (*.png *.jpg *.jpeg *.webp *.tiff *.bmp)"), qsTranslate("App", "All Files (*.*)")]+ onAccepted: {+ if (appBridge && selectedFile) {+ appBridge.selectCustomMask(selectedFile.toString());+ }+ }+ }+}diff --git a/src/desktop/qml/components/PlaybackVolume.js b/src/desktop/qml/components/PlaybackVolume.jsnew file mode 100644index 0000000..e48ce7d--- /dev/null+++ b/src/desktop/qml/components/PlaybackVolume.js@@ -0,0 +1,23 @@+.pragma library++// Qt audio outputs take linear gain. Normalize Qt's logarithmic volume curve+// (whose linear-to-log range ends at 0.99) so the UI has exact 0/100 endpoints+// and every integer slider value survives conversion back from audio gain.+var logarithmicRange = 0.99+var logarithmicBase = Math.log(100)++function gainForLevel(level) {+ if (!isFinite(level)) return 0+ var position = Math.max(0, Math.min(100, level)) / 100+ if (position === 0) return 0+ if (position === 1) return 1+ return -Math.log(1 - logarithmicRange * position) / logarithmicBase+}++function levelForGain(gain) {+ if (!isFinite(gain)) return 0+ var linear = Math.max(0, Math.min(1, gain))+ if (linear === 0) return 0+ if (linear === 1) return 100+ return Math.round((1 - Math.exp(-linear * logarithmicBase)) / logarithmicRange * 100)+}diff --git a/src/desktop/qml/components/PlaybackVolumeControl.qml b/src/desktop/qml/components/PlaybackVolumeControl.qmlnew file mode 100644index 0000000..68959d9--- /dev/null+++ b/src/desktop/qml/components/PlaybackVolumeControl.qml@@ -0,0 +1,193 @@+import QtQuick+import QtQuick.Controls as QQC2+import QtQuick.Controls.Basic as Basic+import "PlaybackVolume.js" as PlaybackVolume+import ".."+import "../controls"++Item {+ id: control+ property var audioOutput: null+ property int buttonSize: 28+ readonly property int storedLevel: audioOutput ? PlaybackVolume.levelForGain(audioOutput.volume) : 0+ readonly property bool silenced: !audioOutput || audioOutput.muted || storedLevel === 0+ readonly property int volumeLevel: silenced ? 0 : storedLevel+ property int lastNonZeroLevel: 80+ property bool keyboardAdjusting: false++ implicitWidth: buttonSize; implicitHeight: buttonSize+ width: implicitWidth; height: implicitHeight+ enabled: !!audioOutput+ LayoutMirroring.enabled: false+ LayoutMirroring.childrenInherit: true++ onStoredLevelChanged: { if (storedLevel > 0) lastNonZeroLevel = storedLevel }+ onEnabledChanged: { if (!enabled) volumePopup.close() }+ Component.onCompleted: { if (storedLevel > 0) lastNonZeroLevel = storedLevel }++ function setVolume(level) {+ if (!audioOutput || !isFinite(level)) return+ var next = Math.round(Math.max(0, Math.min(100, level)))+ if (next > 0) lastNonZeroLevel = next+ audioOutput.volume = PlaybackVolume.gainForLevel(next)+ audioOutput.muted = next === 0+ }+ function toggleMute() {+ if (!audioOutput) return+ if (silenced) {+ if (storedLevel === 0) audioOutput.volume = PlaybackVolume.gainForLevel(lastNonZeroLevel)+ audioOutput.muted = false+ } else {+ audioOutput.muted = true+ }+ }+ function openVolume(keyboard) {+ if (!enabled) return+ closeTimer.stop()+ volumePopup.open()+ if (keyboard) {+ keyboardAdjusting = true+ volumeSlider.forceActiveFocus(Qt.TabFocusReason)+ }+ }++ AppIconButton {+ id: volumeButton+ objectName: "timelineMute"+ buttonSize: control.buttonSize+ iconSize: 18+ iconName: control.silenced ? "mute" : (control.storedLevel <= 50 ? "volume_down" : "volume_up")+ tooltipText: control.silenced ? qsTranslate("App", "Unmute") : qsTranslate("App", "Mute")+ showTooltip: false+ onClicked: control.toggleMute()+ Keys.onPressed: (event) => {+ if (!control.enabled) return+ if (event.key === Qt.Key_Up || event.key === Qt.Key_Down+ || event.key === Qt.Key_Left || event.key === Qt.Key_Right) {+ var up = event.key === Qt.Key_Up || event.key === Qt.Key_Right+ control.setVolume(control.volumeLevel + (up ? 5 : -5))+ control.openVolume(true)+ event.accepted = true+ }+ }+ MouseArea {+ anchors.fill: parent+ acceptedButtons: Qt.NoButton+ onWheel: (wheel) => {+ var delta = wheel.angleDelta.y || wheel.pixelDelta.y+ if (!delta || !control.enabled) return+ control.setVolume(control.volumeLevel + (delta > 0 ? 5 : -5))+ wheel.accepted = true+ }+ }+ }++ HoverHandler {+ id: buttonHover+ enabled: control.enabled+ onHoveredChanged: {+ if (hovered) control.openVolume(false)+ else closeTimer.restart()+ }+ }+ Timer {+ id: closeTimer+ interval: 250+ onTriggered: {+ if (!buttonHover.hovered && !popupHover.hovered && !contentHover.hovered+ && !volumeSlider.pressed && !control.keyboardAdjusting)+ volumePopup.close()+ }+ }++ QQC2.Popup {+ id: volumePopup+ objectName: "timelineVolumePopup"+ parent: control+ x: (control.width - width) / 2; y: -height - 6+ width: 164; height: 44+ padding: 10; margins: 8+ modal: false; focus: false+ closePolicy: QQC2.Popup.CloseOnEscape | QQC2.Popup.CloseOnPressOutsideParent+ onClosed: { closeTimer.stop(); control.keyboardAdjusting = false }+ background: Rectangle {+ color: Theme.bgSurface; radius: Theme.radiusSmall+ border.color: Theme.borderDefault; border.width: 1+ HoverHandler {+ id: popupHover+ onHoveredChanged: {+ if (hovered) closeTimer.stop()+ else closeTimer.restart()+ }+ }+ }+ contentItem: Row {+ spacing: 8+ LayoutMirroring.enabled: false+ LayoutMirroring.childrenInherit: true+ HoverHandler {+ id: contentHover+ onHoveredChanged: {+ if (hovered) closeTimer.stop()+ else closeTimer.restart()+ }+ }+ Basic.Slider {+ id: volumeSlider+ objectName: "timelineVolumeSlider"+ width: 112; height: 24; padding: 0+ from: 0; to: 100; stepSize: 1+ snapMode: Basic.Slider.SnapAlways+ value: control.volumeLevel+ enabled: control.enabled+ live: true; hoverEnabled: true+ focusPolicy: Qt.StrongFocus+ Accessible.name: qsTranslate("App", "Volume")+ onMoved: control.setVolume(value)+ onPressedChanged: {+ if (pressed) { control.keyboardAdjusting = false; closeTimer.stop() }+ else closeTimer.restart()+ }+ onActiveFocusChanged: {+ if (!activeFocus) { control.keyboardAdjusting = false; closeTimer.restart() }+ }+ Keys.onPressed: (event) => {+ if (event.key === Qt.Key_Home || event.key === Qt.Key_End) {+ control.setVolume(event.key === Qt.Key_Home ? 0 : 100)+ event.accepted = true+ } else if (event.key === Qt.Key_Escape) {+ volumePopup.close()+ volumeButton.forceActiveFocus()+ event.accepted = true+ }+ }+ background: Rectangle {+ x: 6; y: (volumeSlider.height - height) / 2+ width: volumeSlider.width - 12; height: 4; radius: 2+ color: Theme.bgSelected+ Rectangle {+ width: parent.width * volumeSlider.position+ height: parent.height; radius: 2; color: Theme.accent+ }+ }+ handle: Rectangle {+ x: volumeSlider.visualPosition * (volumeSlider.availableWidth - width)+ y: (volumeSlider.height - height) / 2+ implicitWidth: 12; implicitHeight: 12+ width: implicitWidth; height: implicitHeight; radius: 6+ color: Theme.textPrimary+ border.color: volumeSlider.pressed || volumeSlider.activeFocus ? Theme.accent : Theme.borderActive+ border.width: 2+ }+ }+ Text {+ objectName: "timelineVolumeReadout"+ width: 24; height: 24+ text: control.volumeLevel+ color: Theme.textPrimary+ font.family: Theme.monoFontFamily; font.pixelSize: Theme.fontSizeSmall+ horizontalAlignment: Text.AlignRight; verticalAlignment: Text.AlignVCenter+ }+ }+ }+}diff --git a/src/desktop/qml/components/RtxVideoHdrControls.qml b/src/desktop/qml/components/RtxVideoHdrControls.qmlnew file mode 100644index 0000000..9bec3b4--- /dev/null+++ b/src/desktop/qml/components/RtxVideoHdrControls.qml@@ -0,0 +1,82 @@+import QtQuick+import "../controls"++Column {+ id: root+ objectName: "rtx-video-hdr-controls"+ property var appBridge: null+ width: parent ? parent.width : 320+ spacing: 12++ AppSlider {+ width: parent.width+ label: qsTranslate("App", "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: qsTranslate("App", "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: qsTranslate("App", "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: qsTranslate("App", "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: qsTranslate("App", "HDR Precision")+ model: appBridge ? appBridge.hdrPrecisionChoices : []+ currentValue: appBridge ? appBridge.upscaleHdrPrecision : "Packed 10-bit"+ onActivated: v => {+ if (appBridge)+ appBridge.upscaleHdrPrecision = v;+ }+ }+}diff --git a/src/desktop/qml/components/ScaleMethodControls.qml b/src/desktop/qml/components/ScaleMethodControls.qmlindex 565c44b..6976e68 100644--- a/src/desktop/qml/components/ScaleMethodControls.qml+++ b/src/desktop/qml/components/ScaleMethodControls.qml@@ -1,19 +1,19 @@-import QtQuick-import QtQuick.Dialogs-import ".."-import "../controls"--Column {- id: root- property var appBridge: null- readonly property bool isImage: appBridge ? appBridge.nrMode === "Image" : true- width: parent ? parent.width : 320- spacing: 12- AppComboBox {- width: parent.width- label: "Scaling Method"+import QtQuick+import QtQuick.Dialogs+import ".."+import "../controls"++Column {+ id: root+ property var appBridge: null+ readonly property bool isImage: appBridge ? appBridge.nrMode === "Image" : true+ width: parent ? parent.width : 320+ spacing: 12+ AppComboBox {+ width: parent.width+ label: qsTranslate("App", "Scaling Method")model: root.isImage ? (appBridge ? appBridge.imageScalingFilterChoices : ["Lanczos4", "Area", "Bicubic", "Bilinear", "Nearest"])- : (appBridge ? appBridge.videoScalingFilterChoices : ["Spline36", "Lanczos", "Bicubic", "Area", "Bilinear", "EWA Lanczos"])+ : (appBridge ? appBridge.videoScalingFilterChoices : ["Spline36", "Lanczos", "Bicubic", "Area", "Bilinear"])currentValue: root.isImage ? (appBridge ? appBridge.imageScalingFilter : "Lanczos4"): (appBridge ? appBridge.videoScalingFilter : "Spline36")onActivated: v => {@@ -23,18 +23,18 @@ Column {elseappBridge.videoScalingFilter = v;}- }- }-- AppComboBox {- width: parent.width- label: "Scale"+ }+ }++ AppComboBox {+ width: parent.width+ label: qsTranslate("App", "Scale")model: appBridge ? appBridge.nrScaleChoices : []- currentValue: appBridge ? appBridge.upscalingFactor : 1.0- onActivated: v => {- if (appBridge)- appBridge.upscalingFactor = v;- }- }-+ currentValue: appBridge ? appBridge.upscalingFactor : 1.0+ onActivated: v => {+ if (appBridge)+ appBridge.upscalingFactor = v;+ }+ }+}diff --git a/src/desktop/qml/components/SharpeningControls.qml b/src/desktop/qml/components/SharpeningControls.qmlindex 24687e8..e07bc6b 100644--- a/src/desktop/qml/components/SharpeningControls.qml+++ b/src/desktop/qml/components/SharpeningControls.qml@@ -10,7 +10,7 @@ Column {AppComboBox {objectName: "sharpening-method"width: parent.width- label: "Sharpening Method"+ label: qsTranslate("App", "Sharpening Method")model: root.appBridge ? root.appBridge.sharpeningMethodChoices : ["NVIDIA NIS", "AMD CAS"]currentValue: root.appBridge ? root.appBridge.sharpeningMethod : "AMD CAS"onActivated: value => { if (root.appBridge) root.appBridge.sharpeningMethod = value }@@ -19,7 +19,7 @@ Column {AppSlider {objectName: "sharpening-strength"width: parent.width- label: "Sharpness"+ label: qsTranslate("App", "Sharpness")from: 0; to: 100; stepSize: 1; precision: 0; defaultValue: 50; unit: "%"value: root.appBridge ? root.appBridge.casSharpness : 50onValueModified: v => { if (root.appBridge) root.appBridge.casSharpness = Math.round(v) }diff --git a/src/desktop/qml/components/SuperResolutionControls.qml b/src/desktop/qml/components/SuperResolutionControls.qmlindex 57f4dc3..14b84d9 100644--- a/src/desktop/qml/components/SuperResolutionControls.qml+++ b/src/desktop/qml/components/SuperResolutionControls.qml@@ -1,224 +1,122 @@-import QtQuick-import QtQuick.Dialogs-import ".."-import "../controls"--Column {- id: root- property var appBridge: null- readonly property bool isImage: appBridge ? appBridge.nrMode === "Image" : true- width: parent ? parent.width : 320- 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"+import QtQuick+import ".."+import "../controls"++Column {+ id: root+ property var appBridge: null+ objectName: "rtx-super-resolution-controls"+ readonly property bool isImage: appBridge ? appBridge.nrMode === "Image" : true+ width: parent ? parent.width : 320+ spacing: 12++ AppComboBox {+ width: parent.width+ label: qsTranslate("App", "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"+ 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: qsTranslate("App", "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"+ 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: qsTranslate("App", "Scale Factor")visible: appBridge && (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+ 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: 8visible: appBridge && (root.isImage ? appBridge.upscaleImageSizeMode : appBridge.upscaleSizeMode) === "Custom dimensions"-- AppTextField {- width: (parent.width - 8) / 2- label: "Width (px)"++ AppTextField {+ width: (parent.width - 8) / 2+ label: qsTranslate("App", "Width (px)")text: (root.isImage ? (appBridge ? appBridge.upscaleImageWidth : 3840): (appBridge ? appBridge.upscaleWidth : 3840)).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)"+ 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: qsTranslate("App", "Height (px)")text: (root.isImage ? (appBridge ? appBridge.upscaleImageHeight : 2160): (appBridge ? appBridge.upscaleHeight : 2160)).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"+ 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: qsTranslate("App", "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- }-- Column {- visible: !root.isImage- width: parent.width- spacing: 12- Text {- text: "RTX Video HDR"- font.family: Theme.fontFamily- font.pixelSize: Theme.fontSizeSubtitle- color: Theme.textSecondary- }- 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;- }- }- }-}+ 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+ }++}diff --git a/src/desktop/qml/components/VideoTransportBar.qml b/src/desktop/qml/components/VideoTransportBar.qmlindex ee1daaf..8268f49 100644--- a/src/desktop/qml/components/VideoTransportBar.qml+++ b/src/desktop/qml/components/VideoTransportBar.qml@@ -1,35 +1,42 @@import QtQuickimport QtMultimedia+import QtQuick.Controls as QQC2+import QtQuick.Controls.Basic as Basicimport ".."import "../controls"Rectangle {id: root+ LayoutMirroring.enabled: false+ LayoutMirroring.childrenInherit: trueproperty var player: nullproperty 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 var audioOutput: null+ // Use probe metadata until the player has loaded the source.property real fallbackDurationMs: 0property 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.+ // Only user actions refresh the viewport's preview, never playback ticks.signal userScrubbed(real posMs)- // Pre-rendered video preview spans (seconds) painted green for Frame- // Interpolation and timed Upscale previews:- // [{start: 12.0, end: 15.0, url: ...}].property var renderedRanges: []- height: 50- color: Theme.bgSurface- border.color: Theme.borderSubtle- border.width: 1+ readonly property bool stacked: width < 640+ readonly property bool compact: width < 480readonly 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+ readonly property real effectiveDuration: Math.max(0, player && player.duration > 0 ? player.duration : fallbackDurationMs)+ readonly property real effectivePosition: player ? Math.max(0, Math.min(effectiveDuration > 0 ? effectiveDuration : player.position, player.position)) : 0+ readonly property int totalFrames: effectiveDuration > 0 ? Math.max(1, Math.round(effectiveDuration * effectiveFps / 1000)) : 0+ readonly property int currentFrame: frameAt(effectivePosition)+ readonly property bool canSeek: !!player && effectiveDuration > 0+ readonly property real lastFramePosition: framePosition(totalFrames)+ readonly property int timeCellWidth: Math.ceil(timeMetrics.advanceWidth)+ readonly property real rulerLabelGap: Math.max(72, timeCellWidth + 24)+ readonly property real rulerStep: niceInterval(effectiveDuration / 1000 / Math.max(1, Math.floor(timelineFace.width / rulerLabelGap)))++ implicitHeight: stacked ? 108 : 72+ height: implicitHeight+ color: Theme.bgInput+ border.color: Theme.borderSubtle+ border.width: 1function fmt(ms) {var total = Math.max(0, Math.floor(ms / 1000))@@ -40,138 +47,321 @@ Rectangle {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)+ return fmt(ms) + "." + Math.floor(Math.max(0, ms) % 1000 / 100)}function fmtDuration(ms) {return ms > 0 && ms < 1000 ? fmtPrecise(ms) : fmt(ms)}+ function fmtExact(ms) {+ var fraction = Math.max(0, Math.floor(ms)) % 1000+ return fmt(ms) + "." + ("00" + fraction).slice(-3)+ }+ function frameAt(ms) {+ return totalFrames > 0 ? Math.min(totalFrames, Math.max(1, Math.floor(ms * effectiveFps / 1000 + 0.000001) + 1)) : 0+ }+ function fractionAt(ms) {+ return effectiveDuration > 0 && isFinite(ms) ? Math.max(0, Math.min(1, ms / effectiveDuration)) : 0+ }+ function framePosition(frame) {+ // MediaPlayer seeks in integer milliseconds. Round into the selected+ // frame, rather than letting a fractional start truncate into N-1.+ return Math.max(0, Math.min(effectiveDuration, Math.ceil((frame - 1) * 1000 / effectiveFps - 0.000001)))+ }+ function nearestFramePosition(ms) {+ var frame = Math.max(1, Math.min(totalFrames, Math.round(ms * effectiveFps / 1000) + 1))+ return framePosition(frame)+ }+ function niceInterval(seconds) {+ var intervals = [0.1, 0.2, 0.5, 1, 2, 5, 10, 15, 30, 60, 120, 300, 600, 900, 1800, 3600, 7200, 14400, 28800, 86400]+ for (var i = 0; i < intervals.length; ++i) {+ if (seconds <= intervals[i]) return intervals[i]+ }+ return Math.ceil(seconds / 86400) * 86400+ }+ function seekTo(posMs) {+ if (!canSeek) return+ var target = framePosition(frameAt(Math.max(0, Math.min(effectiveDuration, posMs))))+ player.position = target+ userScrubbed(target)+ }+ function jumpTo(end) {+ if (!canSeek) return+ player.pause()+ // Show the last frame instead of seeking past it into end-of-stream.+ seekTo(end ? lastFramePosition : 0)+ }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)+ if (!canSeek) return+ player.pause()+ seekTo(framePosition(Math.max(1, Math.min(totalFrames, currentFrame + frames))))+ }+ function togglePlayback() {+ if (!player) return+ if (player.playbackState === MediaPlayer.PlayingState) player.pause()+ else player.play()+ }++ TextMetrics {+ id: timeMetrics+ font.family: Theme.monoFontFamily+ font.pixelSize: Theme.fontSizeBody+ text: root.fmtDuration(root.effectiveDuration)}Row {- id: transportRow- anchors.fill: parent- anchors.margins: 8- spacing: 7+ id: playbackControls+ objectName: "playbackControls"+ x: 12+ y: root.stacked ? root.height - height - 8 : (root.height - height) / 2+ spacing: root.compact ? 2 : 4- AppIconButton { id: startButton; iconName: "go_to_start"; tooltipText: "Start"; onClicked: { if (root.player) { root.player.pause(); root.player.position = 0; root.userScrubbed(0) } } }- AppIconButton { id: previousFrameButton; iconName: "previous_frame"; tooltipText: "Previous frame"; onClicked: root.stepFrames(-1) }AppIconButton {- id: playPauseButton- tooltipText: root.player && root.player.playbackState === MediaPlayer.PlayingState ? "Pause" : "Play"+ objectName: "timelineStart"+ buttonSize: root.compact ? 20 : 30+ anchors.verticalCenter: parent.verticalCenter+ iconName: "go_to_start"; tooltipText: qsTranslate("App", "Start")+ enabled: root.canSeek+ onClicked: root.jumpTo(false)+ }+ AppIconButton {+ objectName: "timelinePreviousFrame"+ buttonSize: root.compact ? 20 : 30+ anchors.verticalCenter: parent.verticalCenter+ iconName: "previous_frame"; tooltipText: qsTranslate("App", "Previous frame")+ enabled: root.canSeek+ onClicked: root.stepFrames(-1)+ }+ AppIconButton {+ objectName: "timelinePlayPause"+ buttonSize: root.compact ? 28 : 36+ iconSize: 20+ activeColor: Theme.textPrimary+ enabled: !!root.player+ tooltipText: root.player && root.player.playbackState === MediaPlayer.PlayingState ? qsTranslate("App", "Pause") : qsTranslate("App", "Play")iconName: root.player && root.player.playbackState === MediaPlayer.PlayingState ? "pause" : "play"- onClicked: {- if (!root.player) return- if (root.player.playbackState === MediaPlayer.PlayingState) root.player.pause()- else root.player.play()+ onClicked: root.togglePlayback()+ Rectangle {+ z: -1; anchors.fill: parent; radius: Theme.radiusSmall+ color: Theme.bgSurface; border.color: Theme.borderDefault; border.width: 1}}- AppIconButton { id: nextFrameButton; iconName: "next_frame"; tooltipText: "Next frame"; onClicked: root.stepFrames(1) }+ AppIconButton {+ objectName: "timelineNextFrame"+ buttonSize: root.compact ? 20 : 30+ anchors.verticalCenter: parent.verticalCenter+ iconName: "next_frame"; tooltipText: qsTranslate("App", "Next frame")+ enabled: root.canSeek+ onClicked: root.stepFrames(1)+ }+ AppIconButton {+ objectName: "timelineEnd"+ buttonSize: root.compact ? 20 : 30+ anchors.verticalCenter: parent.verticalCenter+ iconName: "go_to_end"; tooltipText: qsTranslate("App", "End")+ enabled: root.canSeek+ onClicked: root.jumpTo(true)+ }+ }- Rectangle {- width: Math.max(96, transportRow.width - startButton.width - previousFrameButton.width- - playPauseButton.width - nextFrameButton.width - timeLabel.implicitWidth- - speedCombo.width - 6 * transportRow.spacing)- 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+ Rectangle {+ visible: !root.stacked+ x: playbackControls.x + playbackControls.width + 12+ y: (root.height - height) / 2+ width: 1; height: 28; color: Theme.borderSubtle+ }++ Basic.Slider {+ id: seekSlider+ objectName: "timelineSeek"+ x: root.stacked ? 12 : playbackControls.x + playbackControls.width + 28+ y: 8+ width: Math.max(0, (root.stacked ? root.width - 12 : metadataControls.x - 16) - x)+ height: 52+ padding: 0+ from: 0; to: Math.max(1, root.effectiveDuration)+ value: root.effectivePosition+ stepSize: 1000 / root.effectiveFps+ snapMode: Basic.Slider.SnapAlways+ enabled: root.canSeek+ live: true+ hoverEnabled: true+ focusPolicy: Qt.StrongFocus+ Accessible.name: qsTranslate("App", "Timeline")+ onMoved: root.seekTo(value)+ Keys.onPressed: (event) => {+ if (event.key === Qt.Key_Left || event.key === Qt.Key_Down) {+ root.stepFrames(-1); event.accepted = true+ } else if (event.key === Qt.Key_Right || event.key === Qt.Key_Up) {+ root.stepFrames(1); event.accepted = true+ } else if (event.key === Qt.Key_Home || event.key === Qt.Key_End) {+ root.jumpTo(event.key === Qt.Key_End); event.accepted = true+ } else if (event.key === Qt.Key_Space) {+ root.togglePlayback(); event.accepted = true+ }+ }++ background: Item {+ id: timelineFace+ x: 6+ width: Math.max(0, seekSlider.width - 12)+ height: seekSlider.height+ opacity: root.canSeek ? 1 : 0.45- // Thin white vertical cutoff line at the moving head+ Repeater {+ model: root.effectiveDuration > 0 ? Math.floor(root.effectiveDuration / 1000 / (root.rulerStep / 4)) + 1 : 1Rectangle {- 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+ required property int index+ x: timelineFace.width * root.fractionAt(index * root.rulerStep / 4 * 1000)+ y: index % 4 === 0 ? 25 : 29+ width: 1; height: index % 4 === 0 ? 7 : 3+ color: index % 4 === 0 ? Theme.textMuted : Theme.borderDefault}}- // Green pre-rendered preview spans. 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))- }+ model: root.effectiveDuration > 0 ? Math.floor(root.effectiveDuration / 1000 / root.rulerStep) + 1 : 1+ Text {+ required property int index+ readonly property real tickMs: index * root.rulerStep * 1000+ readonly property real tickX: timelineFace.width * root.fractionAt(tickMs)+ objectName: "timelineRulerLabel"+ // Avoid colliding with the duration at the end of the ruler.+ visible: index === 0 || timelineFace.width - tickX >= root.rulerLabelGap+ x: Math.max(0, Math.min(timelineFace.width - implicitWidth, tickX - implicitWidth / 2))+ y: 3+ text: root.rulerStep < 1 ? root.fmtPrecise(Math.round(tickMs)) : root.fmt(tickMs)+ font.family: Theme.monoFontFamily; font.pixelSize: Theme.fontSizeSmall+ color: Theme.textSecondary}}- 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)+ Text {+ objectName: "timelineDurationLabel"+ visible: root.effectiveDuration > 0+ anchors.right: parent.right; y: 3+ text: root.fmtDuration(root.effectiveDuration)+ font.family: Theme.monoFontFamily; font.pixelSize: Theme.fontSizeSmall+ color: Theme.textSecondary+ }+ Rectangle {+ visible: root.effectiveDuration > 0+ x: parent.width - 1; y: 25; width: 1; height: 7+ color: Theme.textMuted+ }+ Rectangle {+ id: groove+ objectName: "timelineGroove"+ y: 36; width: parent.width; height: 8; radius: 4+ color: Theme.bgSelected+ Rectangle {+ width: parent.width * seekSlider.position+ height: parent.height+ topLeftRadius: 4; bottomLeftRadius: 4+ topRightRadius: 0; bottomRightRadius: 0+ color: Theme.accent+ }+ // Preview ranges stay green above the played portion.+ Repeater {+ model: root.renderedRanges+ Rectangle {+ required property var modelData+ readonly property real startFraction: root.fractionAt(Number(modelData.start) * 1000)+ readonly property real endFraction: root.fractionAt(Number(modelData.end) * 1000)+ objectName: "timelineRenderedRange"+ x: groove.width * startFraction+ width: Math.max(0, groove.width * (endFraction - startFraction))+ height: groove.height+ topLeftRadius: startFraction === 0 ? 4 : 0+ bottomLeftRadius: topLeftRadius+ topRightRadius: endFraction === 1 ? 4 : 0+ bottomRightRadius: topRightRadius+ color: Theme.success}}- onPressed: (mouse) => seek(mouse.x)- onPositionChanged: (mouse) => { if (pressed) seek(mouse.x) }}}- Text {- id: timeLabel- 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+ handle: Item {+ objectName: "timelinePlayhead"+ x: seekSlider.visualPosition * (seekSlider.availableWidth - width)+ y: 0+ implicitWidth: 12; implicitHeight: seekSlider.height+ width: implicitWidth; height: implicitHeight+ opacity: root.canSeek ? 1 : 0.45+ Rectangle {+ anchors.horizontalCenter: parent.horizontalCenter+ anchors.top: parent.top; anchors.bottom: parent.bottom+ width: 2+ color: Theme.accent+ }+ }++ HoverHandler {+ id: timelineHover+ enabled: seekSlider.enabled+ cursorShape: Qt.PointingHandCursor+ }+ QQC2.ToolTip {+ id: seekTip+ objectName: "timelineSeekTip"+ readonly property real targetMs: seekSlider.pressed ? root.framePosition(root.frameAt(seekSlider.value)) : root.nearestFramePosition(root.effectiveDuration * Math.max(0, Math.min(1, (timelineHover.point.position.x - timelineFace.x) / Math.max(1, timelineFace.width))))+ visible: seekSlider.enabled && (timelineHover.hovered || seekSlider.pressed)+ delay: seekSlider.pressed ? 0 : 180+ x: Math.max(0, Math.min(seekSlider.width - width, (seekSlider.pressed ? seekSlider.handle.x + 6 : timelineHover.point.position.x) - width / 2))+ y: -height - 6+ text: root.fmtExact(targetMs) + "\n" + qsTranslate("App", "Frame %1 of %2").arg(root.frameAt(targetMs)).arg(root.totalFrames)+ leftPadding: 8; rightPadding: 8; topPadding: 5; bottomPadding: 5+ contentItem: Text {+ text: seekTip.text; color: Theme.textPrimary+ font.family: Theme.fontFamily; font.pixelSize: Theme.fontSizeSmall+ }+ background: Rectangle {+ color: Theme.bgInput; radius: Theme.radiusSmall+ border.color: Theme.borderActive; border.width: 1}- color: Theme.textSecondary; font.family: Theme.monoFontFamily; font.pixelSize: Theme.fontSizeSmall}+ }+ Row {+ id: metadataControls+ objectName: "timelineMetadata"+ anchors.right: parent.right; anchors.rightMargin: 12+ y: root.stacked ? root.height - height - 11 : (root.height - height) / 2+ spacing: root.compact ? 8 : 12+ Item {+ objectName: "timelineTimeReadout"+ width: root.compact ? root.timeCellWidth + 12 : root.timeCellWidth * 2 + 20+ height: root.compact ? 32 : 30+ Text {+ objectName: "timelineCurrentTime"+ x: 0; y: root.compact ? 0 : (parent.height - height) / 2+ text: root.fmt(root.effectivePosition)+ font.family: Theme.monoFontFamily; font.pixelSize: Theme.fontSizeBody; font.weight: Font.DemiBold+ color: Theme.textPrimary+ }+ Text {+ objectName: "timelineTotalTime"+ x: root.compact ? 0 : root.timeCellWidth + 8+ y: root.compact ? parent.height - height : (parent.height - height) / 2+ text: "/ " + root.fmtDuration(root.effectiveDuration)+ font.family: Theme.monoFontFamily; font.pixelSize: Theme.fontSizeBody+ color: Theme.textSecondary+ }+ }+ PlaybackVolumeControl {+ objectName: "timelineVolume"+ audioOutput: root.player ? root.audioOutput : null+ buttonSize: root.compact ? 24 : 28+ anchors.verticalCenter: parent.verticalCenter+ }AppComboBox {id: speedCombo- 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+ objectName: "timelineSpeed"+ width: root.compact ? 60 : 72; comboHeight: 30+ anchors.verticalCenter: parent.verticalCenter+ enabled: !!root.player+ dropUp: true+ Accessible.name: qsTranslate("App", "Playback speed")+ model: [{label: "0.5x", value: 0.5}, {label: "1x", value: 1}, {label: "1.5x", value: 1.5}, {label: "2x", value: 2}]+ currentValue: root.player ? root.player.playbackRate : 1onActivated: (v) => { if (root.player) root.player.playbackRate = v }}}diff --git a/src/desktop/qml/components/WorkflowStageCard.qml b/src/desktop/qml/components/WorkflowStageCard.qmlindex 4f028f3..9facdfd 100644--- a/src/desktop/qml/components/WorkflowStageCard.qml+++ b/src/desktop/qml/components/WorkflowStageCard.qml@@ -87,7 +87,7 @@ Item {iconName: "chevron_up"buttonSize: 22anchors.verticalCenter: parent.verticalCenter- tooltipText: "Move " + card.title + " up"+ tooltipText: qsTranslate("App", "Move %1 up").arg(card.title)enabled: card.stageIndex > 0onClicked: {if (card.appBridge)@@ -98,7 +98,7 @@ Item {iconName: "chevron_down"buttonSize: 22anchors.verticalCenter: parent.verticalCenter- tooltipText: "Move " + card.title + " down"+ tooltipText: qsTranslate("App", "Move %1 down").arg(card.title)enabled: card.stageIndex < card.stageCount - 1onClicked: {if (card.appBridge)@@ -109,7 +109,7 @@ Item {iconName: card.collapsed ? "chevron_right" : "chevron_left"buttonSize: 22anchors.verticalCenter: parent.verticalCenter- tooltipText: card.collapsed ? "Expand " + card.title : "Collapse " + card.title+ tooltipText: (card.collapsed ? qsTranslate("App", "Expand %1") : qsTranslate("App", "Collapse %1")).arg(card.title)onClicked: card.collapsed = !card.collapsed}diff --git a/src/desktop/qml/controls/AppComboBox.qml b/src/desktop/qml/controls/AppComboBox.qmlindex ac1d200..f459ef6 100644--- a/src/desktop/qml/controls/AppComboBox.qml+++ b/src/desktop/qml/controls/AppComboBox.qml@@ -24,8 +24,8 @@ Item {function getLabel(item) {if (item === undefined || item === null) return ""- if (typeof item === "object" && item.label !== undefined) return item.label- return item.toString()+ if (typeof item === "object" && item.label !== undefined) return qsTranslate("App", item.label)+ return qsTranslate("App", item.toString())}function getValue(item) {if (item === undefined || item === null) return undefined@@ -41,7 +41,7 @@ Item {}function displayText() {if (currentIndex >= 0 && model && currentIndex < model.length) return getLabel(model[currentIndex])- return currentValue === undefined || currentValue === null || currentValue === "" ? "Select..." : "Unavailable: " + currentValue+ return currentValue === undefined || currentValue === null || currentValue === "" ? qsTranslate("App", "Select...") : qsTranslate("App", "Unavailable: %1").arg(currentValue)}onCurrentValueChanged: syncIndex()onModelChanged: syncIndex()diff --git a/src/desktop/qml/controls/AppFilePicker.qml b/src/desktop/qml/controls/AppFilePicker.qmlindex ea6e5b4..b47dcf2 100644--- a/src/desktop/qml/controls/AppFilePicker.qml+++ b/src/desktop/qml/controls/AppFilePicker.qml@@ -9,7 +9,7 @@ Item {property string selectedPath: ""property bool selectFolder: falseproperty bool enabled: true- property var nameFilters: ["All Files (*.*)"]+ property var nameFilters: [qsTranslate("App", "All Files (*.*)")]signal pathChanged(string path)implicitWidth: 260@@ -67,14 +67,14 @@ Item {}}AppButton {- id: browseBtn; text: "Browse"; iconName: "browse_folder"; width: 88; buttonHeight: Theme.controlHeight; enabled: control.enabled+ id: browseBtn; text: qsTranslate("App", "Browse"); iconName: "browse_folder"; width: 88; buttonHeight: Theme.controlHeight; enabled: control.enabledonClicked: control.selectFolder ? folderDialog.open() : fileDialog.open()}}FolderDialog {id: folderDialog- title: "Select Folder"+ title: qsTranslate("App", "Select Folder")onAccepted: {// NOTE: QML url has no toLocalFile(); pass the URL string and// let Python _clean_path() convert via QUrl.toLocalFile().@@ -85,7 +85,7 @@ Item {}FileDialog {id: fileDialog- title: "Select File"+ title: qsTranslate("App", "Select File")fileMode: FileDialog.OpenFilenameFilters: control.nameFiltersonAccepted: {diff --git a/src/desktop/qml/controls/AppLanguageComboBox.qml b/src/desktop/qml/controls/AppLanguageComboBox.qmlnew file mode 100644index 0000000..c054390--- /dev/null+++ b/src/desktop/qml/controls/AppLanguageComboBox.qml@@ -0,0 +1,130 @@+import QtQuick+import QtQuick.Window+import QtQuick.Controls as QQC2+import QtQuick.Controls.Basic as Basic+import ".."++// Qt's ComboBox provides keyboard navigation, type-ahead and accessibility.+// Autonyms retain their own font and text direction, all aligned to the left.+Item {+ id: control+ property string label: ""+ property var model: []+ property string currentValue: "en_US"+ signal activated(string value)+ implicitWidth: 360+ implicitHeight: languageLabel.implicitHeight + 6 + combo.implicitHeight++ Text {+ id: languageLabel+ width: parent.width+ text: control.label+ color: Theme.textSecondary+ font.family: Theme.fontFamily+ font.pixelSize: Theme.fontSizeLabel+ wrapMode: Text.Wrap+ }+ Basic.ComboBox {+ id: combo+ objectName: "languageComboBox"+ width: parent.width+ anchors.top: languageLabel.bottom+ anchors.topMargin: 6+ implicitHeight: Theme.controlHeight+ model: control.model+ textRole: "label"+ valueRole: "value"+ currentIndex: {+ for (var i = 0; i < control.model.length; ++i)+ if (control.model[i].value === control.currentValue) return i+ return -1+ }+ onActivated: control.activated(currentValue)+ Accessible.name: control.label+ leftPadding: mirrored ? 28 : 10+ rightPadding: mirrored ? 10 : 28+ contentItem: Text {+ objectName: "languageDisplayText"+ text: combo.displayText+ font.family: combo.currentIndex >= 0 ? control.model[combo.currentIndex].fontFamily : Theme.fontFamily+ font.pixelSize: Theme.fontSizeLabel+ color: Theme.textPrimary+ verticalAlignment: Text.AlignVCenter+ horizontalAlignment: Text.AlignLeft+ LayoutMirroring.enabled: false+ elide: Text.ElideRight+ }+ indicator: AppIcon {+ x: combo.mirrored ? 10 : combo.width - width - 10+ y: (combo.height - height) / 2+ iconName: combo.popup.visible ? "chevron_up" : "chevron_down"+ iconSize: 12+ color: Theme.textMuted+ }+ background: Rectangle {+ color: combo.hovered || combo.popup.visible ? Theme.bgInputHover : Theme.bgInput+ radius: Theme.radiusMedium+ border.width: 1+ border.color: combo.activeFocus || combo.popup.visible ? Theme.accent : Theme.borderDefault+ }+ delegate: Basic.ItemDelegate {+ objectName: "languageOption"+ required property var modelData+ required property int index+ width: combo.width - 8+ implicitHeight: Theme.controlHeight+ leftPadding: combo.mirrored ? 22 : 12+ rightPadding: combo.mirrored ? 12 : 22+ highlighted: combo.highlightedIndex === index+ contentItem: Text {+ objectName: "languageOptionText"+ text: modelData.label+ font.family: modelData.fontFamily+ font.pixelSize: Theme.fontSizeLabel+ color: combo.currentIndex === index ? Theme.accent : Theme.textPrimary+ verticalAlignment: Text.AlignVCenter+ horizontalAlignment: Text.AlignLeft+ LayoutMirroring.enabled: false+ elide: Text.ElideRight+ }+ background: Rectangle {+ radius: Theme.radiusSmall+ color: parent.highlighted ? Theme.bgHover : (combo.currentIndex === parent.index ? Theme.bgSelected : "transparent")+ }+ }+ popup: QQC2.Popup {+ objectName: "languagePopup"+ y: combo.height + 4+ width: combo.width+ implicitHeight: Math.min(contentItem.implicitHeight + 8,+ combo.Window.window ? Math.max(120, combo.Window.window.height - combo.mapToItem(null, 0, combo.height).y - 12) : contentItem.implicitHeight + 8)+ margins: 8+ padding: 4+ contentItem: ListView {+ id: languageList+ clip: true+ implicitHeight: contentHeight+ model: combo.popup.visible ? combo.delegateModel : null+ currentIndex: combo.highlightedIndex+ boundsBehavior: Flickable.StopAtBounds+ QQC2.ScrollBar.vertical: Basic.ScrollBar {+ width: 10+ policy: QQC2.ScrollBar.AsNeeded+ visible: languageList.contentHeight > languageList.height + 0.5+ background: Rectangle { color: Theme.bgInput; radius: 4 }+ contentItem: Rectangle {+ implicitWidth: 6; radius: 3+ color: parent.pressed ? Theme.accent : Theme.textMuted+ }+ }+ }+ background: Rectangle {+ color: Theme.bgSurface+ radius: Theme.radiusMedium+ border.color: Theme.borderActive+ border.width: 1+ }+ onOpened: contentItem.positionViewAtIndex(combo.currentIndex, ListView.Contain)+ }+ }+}diff --git a/src/desktop/qml/controls/AppSegmentedControl.qml b/src/desktop/qml/controls/AppSegmentedControl.qmlindex e200ae8..46c1cea 100644--- a/src/desktop/qml/controls/AppSegmentedControl.qml+++ b/src/desktop/qml/controls/AppSegmentedControl.qml@@ -28,8 +28,8 @@ Item {function getLabel(item) {if (item === undefined || item === null) return ""- if (typeof item === "object" && item.label !== undefined) return item.label- return item.toString()+ if (typeof item === "object" && item.label !== undefined) return qsTranslate("App", item.label)+ return qsTranslate("App", item.toString())}function getValue(item) {@@ -82,7 +82,7 @@ Item {y: 2height: parent.height - 4width: (parent.width - 4) / Math.max(1, (control.model ? control.model.length : 1))- x: 2 + Math.max(0, control.currentIndex) * width+ x: 2 + (control.LayoutMirroring.enabled ? Math.max(0, control.model.length - 1 - control.currentIndex) : Math.max(0, control.currentIndex)) * widthvisible: control.currentIndex >= 0radius: Theme.radiusSmallcolor: Theme.bgCarddiff --git a/src/desktop/qml/controls/AppSlider.qml b/src/desktop/qml/controls/AppSlider.qmlindex d69dbd0..fd81016 100644--- a/src/desktop/qml/controls/AppSlider.qml+++ b/src/desktop/qml/controls/AppSlider.qml@@ -19,7 +19,48 @@ Item {implicitWidth: 260implicitHeight: 48opacity: enabled ? 1.0 : 0.45- activeFocusOnTab: enabled+ activeFocusOnTab: false++ function formatNumber(number) {+ // Normalize floating-point residue and negative zero in the readout.+ var rounded = Number(number.toFixed(control.precision))+ return rounded.toFixed(control.precision)+ }++ function syncNumber() {+ if (!numberInput) return+ numberInput.dirty = false+ numberInput.text = formatNumber(control.value)+ }++ function parseNumber(text) {+ var normalized = text.trim().replace(/\u2212/g, "-")+ normalized = normalized.replace(/[\u0660-\u0669\u06f0-\u06f9\u0966-\u096f]/g, function(digit) {+ var code = digit.charCodeAt(0)+ var zero = code >= 0x0966 ? 0x0966 : (code >= 0x06f0 ? 0x06f0 : 0x0660)+ return String(code - zero)+ }).replace(/[,\u066b]/g, ".")+ if (!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)$/.test(normalized)) return NaN+ return Number(normalized)+ }++ function commitNumber() {+ if (!numberInput.dirty) return+ var next = parseNumber(numberInput.text)+ numberInput.dirty = false+ if (control.enabled && isFinite(next)) {+ next = Math.max(control.from, Math.min(control.to, next))+ // Manual values use the control's precision, without snapping to+ // the coarser step used for dragging or keyboard increments.+ next = Number(next.toFixed(control.precision))+ if (next !== control.value) control.valueModified(next)+ }+ syncNumber()+ }++ onValueChanged: syncNumber()+ onPrecisionChanged: syncNumber()+ Component.onCompleted: syncNumber()function keyboardStep(direction) {var step = stepSize > 0 ? stepSize : (to - from) / 100@@ -27,14 +68,14 @@ Item {valueModified(next)}Keys.onPressed: (event) => {- if (!enabled) return+ if (!enabled || numberInput.activeFocus) returnif (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+ // Top row: Label, Reset icon, and editable numeric readout.Row {id: headerRowanchors.top: parent.top@@ -44,7 +85,9 @@ Item {Text {id: labelText+ width: Math.min(implicitWidth, Math.max(0, headerRow.width - valueDisplayRow.implicitWidth - 8))text: control.label+ elide: Text.ElideRightfont.family: Theme.fontFamilyfont.pixelSize: Theme.fontSizeLabelcolor: Theme.textSecondary@@ -53,22 +96,27 @@ Item {Item {// Spacer- width: Math.max(8, headerRow.width - labelText.implicitWidth - valueDisplayRow.implicitWidth)+ width: Math.max(8, headerRow.width - labelText.width - valueDisplayRow.implicitWidth)height: 1}Row {id: valueDisplayRowspacing: 6+ LayoutMirroring.enabled: false+ LayoutMirroring.childrenInherit: trueanchors.verticalCenter: parent.verticalCenter- // Reset action+ // Reserve the reset slot so changing away from the default+ // doesn't move the field or its label, including in RTL layouts.Rectangle {+ id: resetButton+ readonly property bool available: Math.abs(control.value - control.defaultValue) > 0.001width: 14height: 14radius: 7color: resetArea.containsMouse ? Theme.bgHover : "transparent"- visible: Math.abs(control.value - control.defaultValue) > 0.001+ opacity: available ? 1.0 : 0.0anchors.verticalCenter: parent.verticalCenterAppIcon {@@ -81,7 +129,8 @@ Item {MouseArea {id: resetAreaanchors.fill: parent- hoverEnabled: control.enabled+ enabled: control.enabled && resetButton.available+ hoverEnabled: enabledcursorShape: Qt.PointingHandCursoronClicked: {control.valueModified(control.defaultValue)@@ -89,16 +138,81 @@ Item {}}- 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+ Item {+ width: numberBox.width+ height: headerRow.heightanchors.verticalCenter: parent.verticalCenter++ Rectangle {+ id: numberBox+ // Keep the same size for every value and editing state.+ width: 44+ height: parent.height+ radius: 3+ color: numberInput.activeFocus || numberHover.hovered ? Theme.bgInput : "transparent"+ border.width: 1+ border.color: numberInput.activeFocus ? Theme.accent : (numberHover.hovered ? Theme.borderDefault : "transparent")++ HoverHandler {+ id: numberHover+ enabled: control.enabled+ cursorShape: Qt.IBeamCursor+ }++ TextInput {+ id: numberInput+ objectName: "sliderNumberInput"+ property bool dirty: false+ anchors.fill: parent+ anchors.leftMargin: 4+ anchors.rightMargin: 4+ enabled: control.enabled+ activeFocusOnTab: control.enabled+ 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+ horizontalAlignment: TextInput.AlignLeft+ verticalAlignment: TextInput.AlignVCenter+ selectByMouse: true+ selectionColor: Theme.accent+ selectedTextColor: "#FFFFFF"+ clip: true+ maximumLength: 24+ inputMethodHints: Qt.ImhFormattedNumbersOnly+ Accessible.name: control.label+ Accessible.description: control.unit+ // Allow an unfinished sign/decimal while typing. Validate+ // the complete number when committing, then clamp it.+ validator: RegularExpressionValidator {+ regularExpression: /\s*[+\-−]?[0-9٠-٩۰-۹०-९]*([.,٫][0-9٠-٩۰-۹०-९]*)?\s*/+ }+ onTextEdited: dirty = true+ onActiveFocusChanged: {+ if (activeFocus) {+ Qt.callLater(function() { if (numberInput.activeFocus) numberInput.selectAll() })+ }+ }+ onEditingFinished: control.commitNumber()+ Keys.onPressed: (event) => {+ if (event.key === Qt.Key_Return || event.key === Qt.Key_Enter) {+ control.commitNumber()+ control.forceActiveFocus()+ event.accepted = true+ } else if (event.key === Qt.Key_Escape) {+ control.syncNumber()+ control.forceActiveFocus()+ event.accepted = true+ } else if (event.key === Qt.Key_Up || event.key === Qt.Key_Down) {+ control.commitNumber()+ control.keyboardStep(event.key === Qt.Key_Up ? 1 : -1)+ control.syncNumber()+ selectAll()+ event.accepted = true+ }+ }+ }+ }}}}@@ -106,6 +220,9 @@ Item {// Slider track & thumbItem {id: trackArea+ // Keep the numeric axis and pointer math consistent in RTL layouts.+ LayoutMirroring.enabled: false+ LayoutMirroring.childrenInherit: trueanchors.left: parent.leftanchors.right: parent.rightanchors.bottom: parent.bottom@@ -148,7 +265,7 @@ Item {height: 14radius: 7color: sliderMouse.containsMouse || sliderMouse.drag.active ? "#FFFFFF" : Theme.textPrimary- border.color: control.activeFocus || sliderMouse.drag.active ? Theme.accent : Theme.borderActive+ border.color: control.activeFocus || numberInput.activeFocus || sliderMouse.drag.active ? Theme.accent : Theme.borderActiveborder.width: 2Rectangle {@@ -167,6 +284,7 @@ Item {MouseArea {id: sliderMouseanchors.fill: parent+ enabled: control.enabledhoverEnabled: control.enabledcursorShape: control.enabled ? Qt.PointingHandCursor : Qt.ArrowCursor@@ -183,7 +301,10 @@ Item {}onPressed: (mouse) => {- if (control.enabled) updateValue(mouse.x)+ if (control.enabled) {+ control.forceActiveFocus(Qt.MouseFocusReason)+ updateValue(mouse.x)+ }}onPositionChanged: (mouse) => {diff --git a/src/desktop/qml/controls/AppSwitch.qml b/src/desktop/qml/controls/AppSwitch.qmlindex fc1d405..67438c8 100644--- a/src/desktop/qml/controls/AppSwitch.qml+++ b/src/desktop/qml/controls/AppSwitch.qml@@ -36,7 +36,7 @@ Item {Rectangle {id: thumby: 2- x: control.checked ? (track.width - width - 2) : 2+ x: control.checked !== control.LayoutMirroring.enabled ? (track.width - width - 2) : 2width: 16height: 16radius: 8diff --git a/src/desktop/qml/views/AboutView.qml b/src/desktop/qml/views/AboutView.qmlindex 5a0223b..68f7885 100644--- a/src/desktop/qml/views/AboutView.qml+++ b/src/desktop/qml/views/AboutView.qml@@ -20,22 +20,22 @@ Rectangle {}Text {anchors.horizontalCenter: parent.horizontalCenter- text: "Advanced neural image & video processing"; font.family: Theme.fontFamily; font.pixelSize: Theme.fontSizeLabel; color: Theme.textSecondary+ text: qsTranslate("App", "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"; iconName: "github"; onClicked: Qt.openUrlExternally("https://github.com/Merserk/dlss5-visual-enhancer") }- AppButton { text: "Support on Patreon"; iconName: "heart"; onClicked: Qt.openUrlExternally("https://www.patreon.com/Merserk") }- AppButton { text: "Third-Party Licenses"; onClicked: { if (root.appBridge) root.appBridge.openThirdPartyNotices() } }+ AppButton { text: qsTranslate("App", "GitHub Repository"); iconName: "github"; onClicked: Qt.openUrlExternally("https://github.com/Merserk/dlss5-visual-enhancer") }+ AppButton { text: qsTranslate("App", "Support on Patreon"); iconName: "heart"; onClicked: Qt.openUrlExternally("https://www.patreon.com/Merserk") }+ AppButton { text: qsTranslate("App", "Third-Party Licenses"); onClicked: { if (root.appBridge) root.appBridge.openThirdPartyNotices() } }}Text {anchors.horizontalCenter: parent.horizontalCenter- text: "Includes Qt/PySide6 under LGPLv3 and other open-source components. See Third-Party Licenses."+ text: qsTranslate("App", "Uses Qt under LGPLv3. See Third-Party Licenses.")font.family: Theme.fontFamily; font.pixelSize: Theme.fontSizeSmall; color: Theme.textSecondary}- 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 }+ Text { anchors.horizontalCenter: parent.horizontalCenter; text: qsTranslate("App", "© 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.qmlindex 37e2074..5452a58 100644--- a/src/desktop/qml/views/FrameInterpolationView.qml+++ b/src/desktop/qml/views/FrameInterpolationView.qml@@ -34,7 +34,7 @@ Item {appBridge: root.appBridgequeueModel: root.appBridge ? root.appBridge.fiQueue : nullhidden: appBridge ? appBridge.focusPreview : false- expandedHeight: appBridge ? appBridge.queueHeight : 190+ expandedHeight: appBridge ? appBridge.queueHeight : 330}}@@ -85,7 +85,7 @@ Item {// Card 1: Frame Generation ConfigurationAppCard {width: parent.width- title: "DLSS Frame Generation"+ title: qsTranslate("App", "DLSS Frame Generation")Column {width: parent.width@@ -93,7 +93,7 @@ Item {AppComboBox {width: parent.width- label: "Target Output Frame Rate"+ label: qsTranslate("App", "Target Output Frame Rate")model: appBridge ? appBridge.fiFpsChoices : []currentValue: appBridge ? appBridge.fiTargetFps : "60"onActivated: (v) => { if (appBridge) appBridge.fiTargetFps = v }@@ -101,7 +101,7 @@ Item {AppSegmentedControl {width: parent.width- label: "DLSS-G Engine"+ label: qsTranslate("App", "DLSS-G Engine")model: appBridge ? appBridge.fiEngineChoices : []currentValue: appBridge ? appBridge.fiEngine : "Auto"onActivated: (v) => { if (appBridge) appBridge.fiEngine = v }@@ -121,7 +121,7 @@ Item {// Card 2: Export SettingsAppCard {width: parent.width- title: "Encoding & Output"+ title: qsTranslate("App", "Encoding & Output")Column {width: parent.width@@ -129,23 +129,25 @@ Item {AppComboBox {width: parent.width- label: "Video Codec"+ label: qsTranslate("App", "Video Codec")model: appBridge ? appBridge.codecChoices : []currentValue: appBridge ? appBridge.fiCodec : "H.264 (NVIDIA NVENC)"onActivated: (v) => { if (appBridge) appBridge.fiCodec = v }}AppComboBox {+ objectName: "fiContainerSelector"width: parent.width- label: "Container (automatic)"- model: appBridge ? appBridge.containerChoices : []+ label: qsTranslate("App", "Container")+ model: appBridge ? appBridge.fiContainerChoices : []currentValue: appBridge ? appBridge.fiContainer : "MP4"- enabled: false+ enabled: !!appBridge+ onActivated: (v) => { if (appBridge) appBridge.fiContainer = v }}AppComboBox {width: parent.width- label: "Quality Preset"+ label: qsTranslate("App", "Quality Preset")visible: !appBridge || appBridge.fixedQualityCodecs.indexOf(appBridge.fiCodec) < 0model: appBridge ? appBridge.encodingQualityChoices : []currentValue: appBridge ? appBridge.fiQuality : "Auto (Default)"@@ -154,13 +156,13 @@ Item {Text {visible: appBridge && appBridge.fixedQualityCodecs.indexOf(appBridge.fiCodec) >= 0- text: "Quality Preset: Fixed by codec"+ text: qsTranslate("App", "Quality Preset: Fixed by codec")color: Theme.textSecondaryfont.pixelSize: Theme.fontSizeSmall}AppCheckBox {- label: "Preserve 10-bit HDR"+ label: qsTranslate("App", "Preserve 10-bit HDR")checked: appBridge ? appBridge.fiHdrMode : falseenabled: appBridge ? appBridge.fiHdrSupported : falseonToggled: (c) => { if (appBridge) appBridge.fiHdrMode = c }@@ -190,7 +192,7 @@ Item {spacing: 8AppButton {- text: "Preview"+ text: qsTranslate("App", "Preview")iconName: "preview"width: Math.max(100, parent.width - 156)buttonHeight: 30@@ -210,20 +212,20 @@ Item {AppIconButton {iconName: "reset"buttonSize: 30- tooltipText: "Reset interpolation settings"+ tooltipText: qsTranslate("App", "Reset interpolation settings")onClicked: { if (appBridge) appBridge.resetTabSettings("frame-interpolation") }}AppIconButton {iconName: "outputs_folder"buttonSize: 30- tooltipText: "Open outputs folder"+ tooltipText: qsTranslate("App", "Open outputs folder")onClicked: { if (appBridge) appBridge.openFolder("") }}}AppButton {- text: appBridge && appBridge.canStop ? "Stop" : "Interpolate Video(s)"+ text: appBridge && appBridge.canStop ? qsTranslate("App", "Stop") : qsTranslate("App", "Interpolate Video(s)")iconName: appBridge && appBridge.canStop ? "stop" : "start_render"variant: appBridge && appBridge.canStop ? "danger" : "primary"width: parent.widthdiff --git a/src/desktop/qml/views/LiveView.qml b/src/desktop/qml/views/LiveView.qmlindex ec5a805..b275c41 100644--- a/src/desktop/qml/views/LiveView.qml+++ b/src/desktop/qml/views/LiveView.qml@@ -89,7 +89,7 @@ Item {}Text {- text: appBridge && appBridge.isLiveRunning ? "LIVE STREAM ACTIVE" : "LIVE ENGINE STANDBY"+ text: appBridge && appBridge.isLiveRunning ? qsTranslate("App", "LIVE STREAM ACTIVE") : qsTranslate("App", "LIVE ENGINE STANDBY")font.family: Theme.fontFamilyfont.pixelSize: Theme.fontSizeTitlefont.weight: Font.Bold@@ -155,8 +155,8 @@ Item {Text {text: appBridge && appBridge.operationState === "LiveStarting"- ? "Loading... Please wait."- : "Buffering... Please wait."+ ? qsTranslate("App", "Loading... Please wait.")+ : qsTranslate("App", "Buffering... Please wait.")font.family: Theme.fontFamilyfont.pixelSize: Theme.fontSizeBodycolor: Theme.textSecondary@@ -174,7 +174,7 @@ Item {AppButton {width: 96buttonHeight: 32- text: appBridge && appBridge.mpvEmbed && appBridge.mpvEmbed.paused ? "Resume" : "Pause"+ text: appBridge && appBridge.mpvEmbed && appBridge.mpvEmbed.paused ? qsTranslate("App", "Resume") : qsTranslate("App", "Pause")iconName: appBridge && appBridge.mpvEmbed && appBridge.mpvEmbed.paused ? "play" : "pause"enabled: appBridge && appBridge.isLiveRunningonClicked: { if (appBridge && appBridge.mpvEmbed) appBridge.mpvEmbed.togglePause() }@@ -182,7 +182,7 @@ Item {AppButton {width: 96buttonHeight: 32- text: appBridge && appBridge.mpvEmbed && appBridge.mpvEmbed.muted ? "Unmute" : "Mute"+ text: appBridge && appBridge.mpvEmbed && appBridge.mpvEmbed.muted ? qsTranslate("App", "Unmute") : qsTranslate("App", "Mute")iconName: appBridge && appBridge.mpvEmbed && appBridge.mpvEmbed.muted ? "volume_up" : "mute"enabled: appBridge && appBridge.isLiveRunningonClicked: { if (appBridge && appBridge.mpvEmbed) appBridge.mpvEmbed.toggleMute() }@@ -190,13 +190,13 @@ Item {AppIconButton {buttonSize: 32iconName: "volume_down"- tooltipText: "Volume down"+ tooltipText: qsTranslate("App", "Volume down")enabled: appBridge && appBridge.isLiveRunningonClicked: { if (appBridge && appBridge.mpvEmbed) appBridge.mpvEmbed.volumeDown() }}Text {width: 56- text: appBridge && appBridge.mpvEmbed ? "Vol " + appBridge.mpvEmbed.volume : "Vol -"+ text: qsTranslate("App", "Vol %1").arg(appBridge && appBridge.mpvEmbed ? appBridge.mpvEmbed.volume : "-")font.family: Theme.monoFontFamilyfont.pixelSize: Theme.fontSizeSmallcolor: Theme.textSecondary@@ -207,7 +207,7 @@ Item {AppIconButton {buttonSize: 32iconName: "volume_up"- tooltipText: "Volume up"+ tooltipText: qsTranslate("App", "Volume up")enabled: appBridge && appBridge.isLiveRunningonClicked: { if (appBridge && appBridge.mpvEmbed) appBridge.mpvEmbed.volumeUp() }}@@ -221,7 +221,7 @@ Item {AppButton {width: 104buttonHeight: 32- text: root.videoExpanded ? "Restore" : "Expand"+ text: root.videoExpanded ? qsTranslate("App", "Restore") : qsTranslate("App", "Expand")iconName: root.videoExpanded ? "collapse" : "expand"enabled: appBridge && appBridge.isLiveRunningonClicked: { root.videoExpanded = !root.videoExpanded; Qt.callLater(root.syncLiveVideo) }@@ -229,7 +229,7 @@ Item {AppButton {width: 124buttonHeight: 32- text: appBridge && appBridge.mpvEmbed && appBridge.mpvEmbed.fullscreen ? "Exit Full" : "Full Screen"+ text: appBridge && appBridge.mpvEmbed && appBridge.mpvEmbed.fullscreen ? qsTranslate("App", "Exit Full") : qsTranslate("App", "Full Screen")iconName: appBridge && appBridge.mpvEmbed && appBridge.mpvEmbed.fullscreen ? "exit_fullscreen" : "fullscreen"enabled: appBridge && appBridge.isLiveRunningonClicked: { if (appBridge && appBridge.mpvEmbed) appBridge.mpvEmbed.toggleFullscreen() }@@ -238,11 +238,12 @@ Item {}Connections {- target: Window.window+ target: root.Window.windowfunction onXChanged() { root.syncLiveVideo() }function onYChanged() { root.syncLiveVideo() }function onWidthChanged() { root.syncLiveVideo() }function onHeightChanged() { root.syncLiveVideo() }+ function onScreenChanged() { Qt.callLater(root.syncLiveVideo) }}Connections {@@ -271,12 +272,12 @@ Item {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: qsTranslate("App", "SOURCE"), value: appBridge && appBridge.liveSourceFps > 0 ? appBridge.liveSourceFps.toFixed(2) + " fps" : "-" },+ { label: qsTranslate("App", "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" }+ { label: qsTranslate("App", "ENCODE"), value: appBridge && appBridge.liveEncodeMs > 0 ? appBridge.liveEncodeMs.toFixed(1) + " ms" : "-" },+ { label: qsTranslate("App", "DROPPED"), value: appBridge ? String(appBridge.liveDroppedFrames) : "0" },+ { label: qsTranslate("App", "REBUFFER"), value: appBridge ? String(appBridge.liveRebufferEvents) : "0" }]delegate: Rectangle {required property var modelData@@ -320,7 +321,7 @@ Item {Text {id: telemetryTextwidth: parent.width- text: appBridge ? appBridge.liveStatusText : "Idle."+ text: appBridge ? appBridge.liveStatusText : qsTranslate("App", "Idle.")font.family: Theme.monoFontFamilyfont.pixelSize: 13lineHeight: 1.4@@ -348,7 +349,7 @@ Item {onPositionChanged: (mouse) => {if (!pressed || !appBridge) returnvar pt = inspectorResizeHandle.mapToItem(root, mouse.x, mouse.y)- appBridge.inspectorWidth = Math.max(300, Math.min(560, root.width - pt.x))+ appBridge.inspectorWidth = Math.max(300, Math.min(560, root.LayoutMirroring.enabled ? pt.x : root.width - pt.x))}}@@ -374,7 +375,7 @@ Item {// Card 1: Source SelectionAppCard {width: parent.width- title: "Stream Source"+ title: qsTranslate("App", "Stream Source")Column {width: parent.width@@ -390,8 +391,8 @@ Item {AppTextField {visible: root.sourceMode === "Online"width: parent.width- label: "Online Stream URL"- placeholderText: "YouTube, Twitch, or HLS/RTMP URL..."+ label: qsTranslate("App", "Online Stream URL")+ placeholderText: qsTranslate("App", "YouTube, Twitch, or HLS/RTMP URL...")text: root.onlineUrlonTextEdited: (t) => { root.onlineUrl = t }}@@ -399,19 +400,19 @@ Item {AppFilePicker {visible: root.sourceMode === "Local"width: parent.width- label: "Local Video File"- placeholderText: "Select MP4/MKV video..."+ label: qsTranslate("App", "Local Video File")+ placeholderText: qsTranslate("App", "Select MP4/MKV video...")selectedPath: root.localVideoPathnameFilters: [- "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 (*.*)"+ qsTranslate("App", "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)"),+ qsTranslate("App", "All Files (*.*)")]onPathChanged: (p) => { root.localVideoPath = p }}AppComboBox {width: parent.width- label: "Source Quality"+ label: qsTranslate("App", "Source Quality")model: appBridge ? appBridge.liveSourceQualityChoices : []currentValue: root.sourceQualityonActivated: (v) => { root.sourceQuality = v }@@ -419,7 +420,7 @@ Item {AppComboBox {width: parent.width- label: "Max Input Resolution"+ label: qsTranslate("App", "Max Input Resolution")model: appBridge ? appBridge.liveMaxHeightChoices : []currentValue: root.maxHeightonActivated: (v) => { root.maxHeight = v }@@ -427,7 +428,7 @@ Item {AppComboBox {width: parent.width- label: "HLS Segment Duration"+ label: qsTranslate("App", "HLS Segment Duration")model: appBridge ? appBridge.liveSegmentChoices : []currentValue: root.segmentSecondsonActivated: (v) => { root.segmentSeconds = v }@@ -435,7 +436,7 @@ Item {AppComboBox {width: parent.width- label: "Target FPS"+ label: qsTranslate("App", "Target FPS")model: appBridge ? appBridge.liveFpsChoices : []currentValue: root.targetFpsonActivated: (v) => { root.targetFps = v }@@ -443,8 +444,8 @@ Item {AppSlider {width: parent.width- label: "Playback Buffer"- unit: "sec"+ label: qsTranslate("App", "Playback Buffer")+ unit: qsTranslate("App", "sec")from: 2to: 30stepSize: 1@@ -459,7 +460,7 @@ Item {// Card 2: Live AI Neural Controls (Dynamic Live Sync!)AppCard {width: parent.width- title: "Live DLSS Effects"+ title: qsTranslate("App", "Live DLSS Effects")Column {width: parent.width@@ -467,7 +468,7 @@ Item {AppSegmentedControl {width: parent.width- label: "NR Style"+ label: qsTranslate("App", "NR Style")model: appBridge ? appBridge.nrStyleChoices : []currentValue: appBridge ? appBridge.liveNrStyle : "Default"onActivated: (v) => { if (appBridge) appBridge.liveNrStyle = v }@@ -475,7 +476,7 @@ Item {AppSlider {width: parent.width- label: "NR Intensity"+ label: qsTranslate("App", "NR Intensity")from: 0.0to: 2.0stepSize: 0.05@@ -486,7 +487,7 @@ Item {AppSlider {width: parent.width- label: "Shimmer Suppression"+ label: qsTranslate("App", "Shimmer Suppression")from: 0.0to: 1.0stepSize: 0.05@@ -497,7 +498,7 @@ Item {AppSlider {width: parent.width- label: "Local Tone Strength"+ label: qsTranslate("App", "Local Tone Strength")from: 0.0to: 2.0stepSize: 0.05@@ -508,7 +509,7 @@ Item {AppSlider {width: parent.width- label: "Local Structure Strength"+ label: qsTranslate("App", "Local Structure Strength")from: 0.0to: 2.0stepSize: 0.05@@ -517,15 +518,15 @@ Item {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 } }+ AppSlider { width: parent.width; label: qsTranslate("App", "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: qsTranslate("App", "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: qsTranslate("App", "Automatic Mask"); checked: appBridge ? appBridge.liveAutomaticMask : false; onToggled: (v) => { if (appBridge) appBridge.liveAutomaticMask = v } }+ AppSlider { width: parent.width; label: qsTranslate("App", "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: qsTranslate("App", "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: qsTranslate("App", "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: qsTranslate("App", "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: qsTranslate("App", "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: qsTranslate("App", "Live Scale"); model: appBridge ? appBridge.nrScaleChoices : []; currentValue: appBridge ? appBridge.liveUpscalingFactor : 1.0; onActivated: (v) => { if (appBridge) appBridge.liveUpscalingFactor = v } }}}}@@ -548,7 +549,7 @@ Item {AppButton {width: parent.width - 98buttonHeight: 36- text: appBridge && appBridge.operationState === "LiveStarting" ? "Cancel Live Startup" : (appBridge && appBridge.isLiveRunning ? "Stop Live Session" : (appBridge && appBridge.operationState === "LiveStopping" ? "Stopping Live..." : "Start Live Session"))+ text: appBridge && appBridge.operationState === "LiveStarting" ? qsTranslate("App", "Cancel Live Startup") : (appBridge && appBridge.isLiveRunning ? qsTranslate("App", "Stop Live Session") : (appBridge && appBridge.operationState === "LiveStopping" ? qsTranslate("App", "Stopping Live...") : qsTranslate("App", "Start Live Session")))iconName: appBridge && appBridge.canStop ? "stop" : "start_render"variant: appBridge && appBridge.canStop ? "danger" : "primary"enabled: appBridge ? (appBridge.canStartLive || appBridge.canStop) : false@@ -572,7 +573,7 @@ Item {}AppButton {- text: "Reset"+ text: qsTranslate("App", "Reset")iconName: "reset"width: 90buttonHeight: 36diff --git a/src/desktop/qml/views/NeuralRenderingView.qml b/src/desktop/qml/views/NeuralRenderingView.qmlindex 50212c9..f2e2f03 100644--- a/src/desktop/qml/views/NeuralRenderingView.qml+++ b/src/desktop/qml/views/NeuralRenderingView.qml@@ -1,16 +1,16 @@-import QtQuick-import ".."-import "../controls"-import "../components"-+import QtQuick+import ".."+import "../controls"+import "../components"+Item {id: rootobjectName: "neural-rendering-view"property var appBridge: nullproperty alias workflowRepeater: stageRepeater- readonly property int adaptiveInspectorWidth: width >= 2560 ? 520 : (width >= 1920 ? 460 : (width >= 1600 ? 420 : (width >= 1280 ? 380 : 340)))-+ 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") : truereadonly property var activeQueue: appBridge ? (isImage ? appBridge.nrImageQueue : appBridge.nrVideoQueue) : nullproperty var collapsedCards: ({})@@ -36,127 +36,128 @@ Item {&& index >= dragTargetIndex && index < dragOriginIndex) return distancereturn 0}-+function stageTitle(id) {- if (id === "denoising") return "Denoising"- if (id === "neural_model") return "DLSS Neural Rendering"- if (id === "scale_method") return "Scaling"- if (id === "dlss_super_resolution") return "DLSS Super Resolution"- if (id === "super_resolution") return "RTX Super Resolution"- if (id === "coloring") return "Coloring"- if (id === "cas_sharpening") return "Sharpening"- return "DLSS Frame Generation"- }-- Component { id: neuralControls; NeuralModelControls { appBridge: root.appBridge } }+ if (id === "neural_model") return qsTranslate("App", "DLSS Neural Rendering")+ if (id === "scale_method") return qsTranslate("App", "Scaling")+ if (id === "dlss_super_resolution") return qsTranslate("App", "DLSS Super Resolution")+ if (id === "super_resolution") return qsTranslate("App", "RTX Super Resolution")+ if (id === "rtx_video_hdr") return qsTranslate("App", "RTX Video HDR")+ if (id === "coloring") return qsTranslate("App", "Coloring")+ if (id === "cas_sharpening") return qsTranslate("App", "Sharpening")+ return qsTranslate("App", "DLSS Frame Generation")+ }++ Component { id: neuralControls; NeuralModelControls { appBridge: root.appBridge } }Component { id: scaleControls; ScaleMethodControls { appBridge: root.appBridge } }Component { id: dlssControls; DlssSuperResolutionControls { appBridge: root.appBridge } }Component { id: superControls; SuperResolutionControls { appBridge: root.appBridge } }- Component { id: coloringControls; ColoringControls { appBridge: root.appBridge } }- Component { id: denoisingControls; DenoisingControls { appBridge: root.appBridge } }+ Component { id: hdrControls; RtxVideoHdrControls { appBridge: root.appBridge } }+ Component { id: coloringControls; ColoringControls { appBridge: root.appBridge; playheadMs: viewport.playheadMs } }Component { id: sharpeningControls; SharpeningControls { appBridge: root.appBridge } }- Component { id: frameControls; FrameGenerationControls { appBridge: root.appBridge } }-- 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+ Component { id: frameControls; FrameGenerationControls { appBridge: root.appBridge } }++ 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+ imageQueue: root.isImage+ hidden: appBridge ? appBridge.focusPreview : false+ expandedHeight: appBridge ? appBridge.queueHeight : 330+ }+ }++ // 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.LayoutMirroring.enabled ? pt.x : 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 + 24clip: trueboundsBehavior: Flickable.StopAtBoundsinteractive: root.draggedStageId === ""-- Column {- id: contentCol- width: parent.width - 24- anchors.horizontalCenter: parent.horizontalCenter- anchors.top: parent.top- anchors.topMargin: 12- spacing: 12-- Repeater {- id: stageRepeater++ Column {+ id: contentCol+ width: parent.width - 24+ anchors.horizontalCenter: parent.horizontalCenter+ anchors.top: parent.top+ anchors.topMargin: 12+ spacing: 12++ Repeater {+ id: stageRepeatermodel: appBridge ? appBridge.workflowStages : []delegate: WorkflowStageCard {objectName: "workflow-stage-" + stageId@@ -201,102 +202,102 @@ Item {Loader {width: parent.widthsourceComponent: stageId === "neural_model" ? neuralControls- : stageId === "denoising" ? denoisingControls: stageId === "scale_method" ? scaleControls: stageId === "dlss_super_resolution" ? dlssControls: stageId === "super_resolution" ? superControls+ : stageId === "rtx_video_hdr" ? hdrControls: stageId === "coloring" ? coloringControls: stageId === "cas_sharpening" ? sharpeningControls: frameControls- }- }- }-- AppCard {- width: parent.width- title: "Export Settings"- ExportSettingsControls {- width: parent.width- appBridge: root.appBridge- }- }- }- }-- // Sticky Bottom Action Bar- Rectangle {- id: actionBar- width: parent.width- height: 88- color: Theme.bgSurface- border.color: Theme.borderSubtle- border.width: 1-- Column {- anchors.fill: parent- anchors.margins: 8- spacing: 6-- Row {- width: parent.width- spacing: 8-- AppButton {- text: "Preview"- iconName: "preview"- width: Math.max(100, parent.width - (root.isImage ? 84 : 156))- buttonHeight: 30- enabled: appBridge ? appBridge.canPreview : false- onClicked: {- if (appBridge) appBridge.renderPreviewAt(viewport.playheadMs)- }- }-- AppComboBox {- width: 72- comboHeight: 30- dropUp: true- visible: !root.isImage- model: appBridge ? appBridge.nrPreviewLengthChoices : []- currentValue: appBridge ? appBridge.nrPreviewLength : "3"- onActivated: (v) => { if (appBridge) appBridge.nrPreviewLength = v }- }-- AppIconButton {- iconName: "reset"- buttonSize: 30- tooltipText: "Reset neural rendering settings"- onClicked: { if (appBridge) appBridge.resetTabSettings("neural-rendering") }- }-- AppIconButton {- iconName: "outputs_folder"- buttonSize: 30- tooltipText: "Open outputs folder"- onClicked: { if (appBridge) appBridge.openFolder("") }- }- }-- AppButton {- text: appBridge && appBridge.canStop ? "Stop" : (root.isImage ? "Render Image(s)" : "Render Video(s)")- iconName: appBridge && appBridge.canStop ? "stop" : "start_render"- variant: appBridge && appBridge.canStop ? "danger" : "primary"- width: parent.width- buttonHeight: 34- enabled: appBridge ? (appBridge.canStop || (appBridge.operationState === "Idle" && appBridge.runtimeState === "Ready" && !appBridge.isLiveRunning)) : false- onClicked: {- if (appBridge) {- if (appBridge.canStop) {- appBridge.stopActiveBatch()- } else {- appBridge.requestActiveBatchExport()- }- }- }- }- }- }- }- }- }-}+ }+ }+ }++ AppCard {+ width: parent.width+ title: qsTranslate("App", "Export Settings")+ ExportSettingsControls {+ width: parent.width+ appBridge: root.appBridge+ }+ }+ }+ }++ // Sticky Bottom Action Bar+ Rectangle {+ id: actionBar+ width: parent.width+ height: 88+ color: Theme.bgSurface+ border.color: Theme.borderSubtle+ border.width: 1++ Column {+ anchors.fill: parent+ anchors.margins: 8+ spacing: 6++ Row {+ width: parent.width+ spacing: 8++ AppButton {+ text: qsTranslate("App", "Preview")+ iconName: "preview"+ width: Math.max(100, parent.width - (root.isImage ? 84 : 156))+ buttonHeight: 30+ enabled: appBridge ? appBridge.canPreview : false+ onClicked: {+ if (appBridge) appBridge.renderPreviewAt(viewport.playheadMs)+ }+ }++ AppComboBox {+ width: 72+ comboHeight: 30+ dropUp: true+ visible: !root.isImage+ model: appBridge ? appBridge.nrPreviewLengthChoices : []+ currentValue: appBridge ? appBridge.nrPreviewLength : "3"+ onActivated: (v) => { if (appBridge) appBridge.nrPreviewLength = v }+ }++ AppIconButton {+ iconName: "reset"+ buttonSize: 30+ tooltipText: qsTranslate("App", "Reset neural rendering settings")+ onClicked: { if (appBridge) appBridge.resetTabSettings("neural-rendering") }+ }++ AppIconButton {+ iconName: "outputs_folder"+ buttonSize: 30+ tooltipText: qsTranslate("App", "Open outputs folder")+ onClicked: { if (appBridge) appBridge.openFolder("") }+ }+ }++ AppButton {+ text: appBridge && appBridge.canStop ? qsTranslate("App", "Stop") : (root.isImage ? qsTranslate("App", "Render Image(s)") : qsTranslate("App", "Render Video(s)"))+ iconName: appBridge && appBridge.canStop ? "stop" : "start_render"+ variant: appBridge && appBridge.canStop ? "danger" : "primary"+ width: parent.width+ buttonHeight: 34+ enabled: appBridge ? (appBridge.canStop || (appBridge.operationState === "Idle" && appBridge.runtimeState === "Ready" && !appBridge.isLiveRunning)) : false+ onClicked: {+ if (appBridge) {+ if (appBridge.canStop) {+ appBridge.stopActiveBatch()+ } else {+ appBridge.requestActiveBatchExport()+ }+ }+ }+ }+ }+ }+ }+ }+ }+}diff --git a/src/desktop/qml/views/SettingsView.qml b/src/desktop/qml/views/SettingsView.qmlindex 0d511da..be80260 100644--- a/src/desktop/qml/views/SettingsView.qml+++ b/src/desktop/qml/views/SettingsView.qml@@ -11,21 +11,22 @@ Rectangle {color: Theme.bgBaseFlickable {+ id: settingsViewportanchors.fill: parent; anchors.margins: 28contentWidth: width- contentHeight: settingsCol.implicitHeight + 48+ contentHeight: Math.max(height, settingsCol.implicitHeight)clip: true; boundsBehavior: Flickable.StopAtBoundsColumn {id: settingsColwidth: Math.min(parent.width, 1120)anchors.horizontalCenter: parent.horizontalCenter+ y: Math.max(0, (settingsViewport.height - implicitHeight) / 2)spacing: 20Column {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 }+ Text { width: parent.width; horizontalAlignment: Text.AlignHCenter; wrapMode: Text.Wrap; text: qsTranslate("App", "Preferences & System Configuration"); font.family: Theme.fontFamily; font.pixelSize: Theme.fontSizeHeader; font.weight: Font.Bold; color: Theme.textPrimary }}Column {@@ -33,53 +34,104 @@ Rectangle {width: parent.width; spacing: 14AppCard {- width: cardColumn.width; title: "Hardware & GPU Acceleration"; collapsible: false+ width: cardColumn.width; title: qsTranslate("App", "Language"); collapsible: false+ Column {+ width: parent.width; spacing: 10+ AppLanguageComboBox {+ width: parent.width+ label: qsTranslate("App", "Interface Language")+ model: appBridge ? appBridge.languageChoices : [{label: "English (US)", value: "en_US", fontFamily: Theme.fontFamily}]+ currentValue: appBridge ? appBridge.language : "en_US"+ onActivated: (value) => { if (appBridge) appBridge.language = value }+ }+ }+ }++ AppCard {+ width: cardColumn.width; title: qsTranslate("App", "Hardware & GPU Acceleration"); collapsible: falseColumn {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 } }+ AppComboBox {+ width: parent.width; label: qsTranslate("App", "AI Processing GPU (Tensor Cores / NGX)")+ model: appBridge ? appBridge.aiGpuChoices : []+ currentValue: appBridge ? appBridge.aiGpuUuid : "auto"+ onActivated: (v) => { if (appBridge) appBridge.aiGpuUuid = v }+ }+ AppComboBox {+ objectName: "ffmpeg-vulkan-device"+ width: parent.width; label: qsTranslate("App", "Decoding / Encoding Device")+ model: appBridge ? appBridge.ffmpegDeviceChoices : [{label: qsTranslate("App", "Automatic (Best Available)"), value: "auto"}, {label: "CPU", value: "cpu"}]+ currentValue: appBridge ? appBridge.ffmpegDevice : "auto"+ onActivated: (v) => { if (appBridge) appBridge.ffmpegDevice = v }+ }}}AppCard {- width: cardColumn.width; title: "Preview & Rendering Engine"; collapsible: false+ width: cardColumn.width; title: qsTranslate("App", "Cache Memory"); collapsible: false+ Column {+ width: parent.width; spacing: 10+ AppComboBox {+ objectName: "cache-codec"+ width: parent.width; label: qsTranslate("App", "Codec")+ model: [+ {label: "FFV1", value: "FFV1"},+ {label: "ProRes Proxy", value: "ProRes Proxy"}+ ]+ currentValue: appBridge ? appBridge.cacheCodec : "FFV1"+ onActivated: (v) => { if (appBridge) appBridge.cacheCodec = v }+ }+ AppComboBox {+ objectName: "cache-memory-mode"+ width: parent.width+ model: [+ {label: qsTranslate("App", "Stage by Stage"), value: "stage"},+ {label: qsTranslate("App", "Rolling Cache (5 GB)"), value: "rolling"}+ ]+ currentValue: appBridge ? appBridge.cacheMemoryMode : "stage"+ onActivated: (v) => { if (appBridge) appBridge.cacheMemoryMode = v }+ }+ }+ }++ AppCard {+ width: cardColumn.width; title: qsTranslate("App", "Preview"); collapsible: falseColumn {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 } }+ AppSwitch { width: parent.width; label: qsTranslate("App", "Realtime Preview"); checked: appBridge ? appBridge.autoPreviewEnabled : true; enabled: appBridge ? appBridge.runtimeState === "Ready" : false; onToggled: (v) => { if (appBridge) appBridge.autoPreviewEnabled = v } }}}AppCard {- width: cardColumn.width; title: "Settings Presets"; collapsible: false+ width: cardColumn.width; title: qsTranslate("App", "Settings Presets"); collapsible: falseColumn {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 {+ AppTextField { width: parent.width; placeholderText: qsTranslate("App", "Preset name (e.g. 4K Master)..."); text: root.presetName; onTextEdited: (t) => root.presetName = t }+ Flow {+ width: parent.widthspacing: 8AppButton {- text: "Export Preset..."+ text: qsTranslate("App", "Export Preset...")iconName: "export"onClicked: {if (root.presetName.trim().length === 0) { if (appBridge) appBridge.exportPreset(""); return }presetSaveDialog.open()}}- AppButton { text: "Import..."; iconName: "import"; onClicked: presetImportDialog.open() }+ AppButton { text: qsTranslate("App", "Import..."); iconName: "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 }+ Text { visible: appBridge && appBridge.presetStatus !== ""; width: parent.width; wrapMode: Text.Wrap; text: appBridge ? appBridge.presetStatus : ""; font.family: Theme.fontFamily; font.pixelSize: Theme.fontSizeSmall; color: Theme.accent }}}AppCard {- width: cardColumn.width; title: "Maintenance & Defaults"; collapsible: false+ width: cardColumn.width; title: qsTranslate("App", "Maintenance & Defaults"); collapsible: falseColumn {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 {+ Flow {width: parent.width; spacing: 8- AppButton { text: "Open Logs"; iconName: "logs_folder"; onClicked: { if (appBridge) appBridge.openFolder(appBridge.currentLogPath) } }- AppButton { text: "Reset All Settings to Defaults"; iconName: "reset"; variant: "danger"; onClicked: resetDialog.open() }+ AppButton { text: qsTranslate("App", "Open Logs"); iconName: "logs_folder"; onClicked: { if (appBridge) appBridge.openFolder(appBridge.currentLogPath) } }+ AppButton { text: qsTranslate("App", "Reset All Settings to Defaults"); iconName: "reset"; variant: "danger"; onClicked: resetDialog.open() }}}}@@ -88,17 +140,25 @@ Rectangle {}FileDialog {- id: presetImportDialog; title: "Import Preset JSON"; nameFilters: ["JSON Presets (*.json)", "All Files (*.*)"]+ id: presetImportDialog; title: qsTranslate("App", "Import Preset JSON"); nameFilters: [qsTranslate("App", "JSON Presets (*.json)"), qsTranslate("App", "All Files (*.*)")]onAccepted: { if (appBridge && selectedFile) appBridge.importPreset(selectedFile.toString()) }}FileDialog {- id: presetSaveDialog; title: "Export Preset JSON"; fileMode: FileDialog.SaveFile; nameFilters: ["JSON Presets (*.json)"]+ id: presetSaveDialog; title: qsTranslate("App", "Export Preset JSON"); fileMode: FileDialog.SaveFile; nameFilters: [qsTranslate("App", "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+ footer: Item {+ implicitHeight: 48+ Row {+ anchors.right: parent.right; anchors.rightMargin: 20+ anchors.verticalCenter: parent.verticalCenter; spacing: 8+ AppButton { text: qsTranslate("App", "No"); onClicked: resetDialog.reject() }+ AppButton { text: qsTranslate("App", "Yes"); variant: "danger"; onClicked: resetDialog.accept() }+ }+ }leftPadding: 20rightPadding: 20topPadding: 16@@ -107,12 +167,12 @@ Rectangle {// Borderless custom header: the default Dialog title chrome draws// its own light separator line under the title.header: QQC2.Label {- text: "Reset all settings?"+ text: qsTranslate("App", "Reset all settings?")color: Theme.textPrimary; font.family: Theme.fontFamilyfont.pixelSize: Theme.fontSizeTitle; font.weight: Font.BoldleftPadding: 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 }+ contentItem: Text { width: 360; wrapMode: Text.Wrap; text: qsTranslate("App", "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 }diff --git a/src/desktop/qml/views/UpscaleView.qml b/src/desktop/qml/views/UpscaleView.qmlindex 395b83b..0d3fdec 100644--- a/src/desktop/qml/views/UpscaleView.qml+++ b/src/desktop/qml/views/UpscaleView.qml@@ -36,8 +36,9 @@ Item {anchors.right: parent.rightappBridge: root.appBridgequeueModel: root.activeQueue+ imageQueue: root.isImagehidden: appBridge ? appBridge.focusPreview : false- expandedHeight: appBridge ? appBridge.queueHeight : 190+ expandedHeight: appBridge ? appBridge.queueHeight : 330}}@@ -111,7 +112,7 @@ Item {// Card 1: Super ResolutionAppCard {width: parent.width- title: "DLSS Super Resolution"+ title: qsTranslate("App", "DLSS Super Resolution")Column {width: parent.width@@ -119,7 +120,7 @@ Item {AppComboBox {width: parent.width- label: "Engine"+ label: qsTranslate("App", "Engine")model: appBridge ? appBridge.upscaleEngineChoices : []currentValue: root.isImage ? (appBridge ? appBridge.upscaleImageEngine : "RTX Video Super Resolution") : (appBridge ? appBridge.upscaleEngine : "RTX Video Super Resolution")onActivated: (v) => {@@ -132,7 +133,7 @@ Item {AppComboBox {width: parent.width- label: "DLSS Mode"+ label: qsTranslate("App", "DLSS Mode")visible: appBridge && (root.isImage ? appBridge.upscaleImageEngine : appBridge.upscaleEngine) === "DLSS"model: appBridge ? appBridge.dlssModeChoices : []currentValue: root.isImage ? (appBridge ? appBridge.upscaleImageDlssMode : "Quality") : (appBridge ? appBridge.upscaleDlssMode : "Quality")@@ -146,7 +147,7 @@ Item {AppComboBox {width: parent.width- label: "DLSS Preset"+ label: qsTranslate("App", "DLSS Preset")visible: appBridge && (root.isImage ? appBridge.upscaleImageEngine : appBridge.upscaleEngine) === "DLSS"model: appBridge ? appBridge.dlssPresetChoices : []currentValue: root.isImage ? (appBridge ? appBridge.upscaleImageDlssPreset : "Default") : (appBridge ? appBridge.upscaleDlssPreset : "Default")@@ -161,7 +162,7 @@ Item {AppSwitch {visible: !root.isImage&& appBridge && appBridge.upscaleEngine !== "DLSS"- label: "Enable RTX VSR"+ label: qsTranslate("App", "Enable RTX VSR")checked: appBridge ? appBridge.upscaleVsrEnabled : trueenabled: appBridge ? (!checked || appBridge.upscaleHdrEnabled) : trueonToggled: (c) => { if (appBridge) appBridge.upscaleVsrEnabled = c }@@ -169,7 +170,7 @@ Item {AppComboBox {width: parent.width- label: "VSR Quality"+ label: qsTranslate("App", "VSR Quality")visible: !appBridge || (root.isImage ? appBridge.upscaleImageEngine : appBridge.upscaleEngine) !== "DLSS"model: appBridge ? appBridge.vsrQualityChoices : []currentValue: root.isImage ? (appBridge ? appBridge.upscaleImageVsrQuality : 4) : (appBridge ? appBridge.upscaleVsrQuality : 4)@@ -183,7 +184,7 @@ model: appBridge ? appBridge.vsrQualityChoices : []AppSegmentedControl {width: parent.width- label: "Sizing Mode"+ label: qsTranslate("App", "Sizing Mode")visible: !appBridge || (root.isImage ? appBridge.upscaleImageEngine : appBridge.upscaleEngine) !== "DLSS"model: appBridge ? (root.isImage ? appBridge.imageSizeModeChoices : appBridge.videoSizeModeChoices) : []currentValue: root.isImage ? (appBridge ? appBridge.upscaleImageSizeMode : "Scale factor") : (appBridge ? appBridge.upscaleSizeMode : "Scale factor")@@ -197,7 +198,7 @@ model: appBridge ? appBridge.vsrQualityChoices : []AppComboBox {width: parent.width- label: "Scale Factor"+ label: qsTranslate("App", "Scale Factor")visible: appBridge && (root.isImage ? appBridge.upscaleImageEngine : appBridge.upscaleEngine) !== "DLSS" && (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)@@ -216,7 +217,7 @@ model: appBridge ? appBridge.vsrQualityChoices : []AppTextField {width: (parent.width - 8) / 2- label: "Width (px)"+ label: qsTranslate("App", "Width (px)")text: (root.isImage ? appBridge.upscaleImageWidth : appBridge.upscaleWidth).toString()commitOnEveryEdit: falseonTextEdited: (t) => {@@ -230,7 +231,7 @@ model: appBridge ? appBridge.vsrQualityChoices : []AppTextField {width: (parent.width - 8) / 2- label: "Height (px)"+ label: qsTranslate("App", "Height (px)")text: (root.isImage ? appBridge.upscaleImageHeight : appBridge.upscaleHeight).toString()commitOnEveryEdit: falseonTextEdited: (t) => {@@ -244,7 +245,7 @@ model: appBridge ? appBridge.vsrQualityChoices : []}AppCheckBox {- label: "Lock Aspect Ratio"+ label: qsTranslate("App", "Lock Aspect Ratio")visible: !appBridge || (root.isImage ? appBridge.upscaleImageEngine : appBridge.upscaleEngine) !== "DLSS"checked: root.isImage ? (appBridge ? appBridge.upscaleImageAspectLock : true) : (appBridge ? appBridge.upscaleAspectLock : true)onToggled: (c) => {@@ -271,14 +272,14 @@ model: appBridge ? appBridge.vsrQualityChoices : []AppCard {visible: !root.isImagewidth: parent.width- title: "RTX Video HDR"+ title: qsTranslate("App", "RTX Video HDR")Column {width: parent.widthspacing: 12AppSwitch {- label: "Convert SDR to HDR"+ label: qsTranslate("App", "Convert SDR to HDR")checked: appBridge ? appBridge.upscaleHdrEnabled : falseenabled: appBridge ? (appBridge.upscaleHdrSupported && (!checked || appBridge.upscaleVsrEnabled || appBridge.upscaleEngine === "DLSS")) : falseonToggled: (c) => { if (appBridge) appBridge.upscaleHdrEnabled = c }@@ -286,7 +287,7 @@ model: appBridge ? appBridge.vsrQualityChoices : []AppSlider {width: parent.width- label: "HDR Contrast"+ label: qsTranslate("App", "HDR Contrast")from: 0to: 200stepSize: 1@@ -298,7 +299,7 @@ model: appBridge ? appBridge.vsrQualityChoices : []AppSlider {width: parent.width- label: "HDR Saturation"+ label: qsTranslate("App", "HDR Saturation")from: 0to: 200stepSize: 1@@ -310,7 +311,7 @@ model: appBridge ? appBridge.vsrQualityChoices : []AppSlider {width: parent.width- label: "Middle Gray"+ label: qsTranslate("App", "Middle Gray")from: 10to: 100stepSize: 1@@ -322,7 +323,7 @@ model: appBridge ? appBridge.vsrQualityChoices : []AppSlider {width: parent.width- label: "Peak Luminance"+ label: qsTranslate("App", "Peak Luminance")unit: "nits"from: 400to: 2000@@ -335,7 +336,7 @@ model: appBridge ? appBridge.vsrQualityChoices : []AppSegmentedControl {width: parent.width- label: "HDR Precision"+ label: qsTranslate("App", "HDR Precision")model: appBridge ? appBridge.hdrPrecisionChoices : []currentValue: appBridge ? appBridge.upscaleHdrPrecision : "Packed 10-bit"onActivated: (v) => { if (appBridge) appBridge.upscaleHdrPrecision = v }@@ -346,7 +347,7 @@ model: appBridge ? appBridge.vsrQualityChoices : []// Card 3: Export SettingsAppCard {width: parent.width- title: "Export & Formats"+ title: qsTranslate("App", "Export & Formats")Column {width: parent.width@@ -359,7 +360,7 @@ model: appBridge ? appBridge.vsrQualityChoices : []AppComboBox {width: parent.width- label: "Format"+ label: qsTranslate("App", "Format")model: appBridge ? appBridge.imageFormatChoices : []currentValue: appBridge ? appBridge.upscaleImageOutputFormat : "PNG"onActivated: (v) => { if (appBridge) appBridge.upscaleImageOutputFormat = v }@@ -367,7 +368,7 @@ model: appBridge ? appBridge.vsrQualityChoices : []AppSlider {width: parent.width- label: "Quality"+ label: qsTranslate("App", "Quality")from: 1to: 100stepSize: 1@@ -386,15 +387,25 @@ model: appBridge ? appBridge.vsrQualityChoices : []AppComboBox {width: parent.width- label: "Codec"+ label: qsTranslate("App", "Codec")model: appBridge ? appBridge.codecChoices : []currentValue: appBridge ? appBridge.upscaleCodec : "H.265 (NVIDIA NVENC)"onActivated: (v) => { if (appBridge) appBridge.upscaleCodec = v }}AppComboBox {+ objectName: "upscaleContainerSelector"width: parent.width- label: "Quality"+ label: qsTranslate("App", "Container")+ model: appBridge ? appBridge.upscaleContainerChoices : []+ currentValue: appBridge ? appBridge.upscaleContainer : "MKV"+ enabled: !!appBridge+ onActivated: (v) => { if (appBridge) appBridge.upscaleContainer = v }+ }++ AppComboBox {+ width: parent.width+ label: qsTranslate("App", "Quality")visible: !appBridge || appBridge.fixedQualityCodecs.indexOf(appBridge.upscaleCodec) < 0model: appBridge ? appBridge.encodingQualityChoices : []currentValue: appBridge ? appBridge.upscaleQuality : "Auto (Default)"@@ -403,7 +414,7 @@ model: appBridge ? appBridge.vsrQualityChoices : []Text {visible: appBridge && appBridge.fixedQualityCodecs.indexOf(appBridge.upscaleCodec) >= 0- text: "Quality: Fixed by codec"+ text: qsTranslate("App", "Quality: Fixed by codec")color: Theme.textSecondaryfont.pixelSize: Theme.fontSizeSmall}@@ -434,7 +445,7 @@ model: appBridge ? appBridge.vsrQualityChoices : []visible: root.isImageAppButton {- text: "Preview"+ text: qsTranslate("App", "Preview")iconName: "preview"width: (parent.width - 16) / 3buttonHeight: 30@@ -445,7 +456,7 @@ model: appBridge ? appBridge.vsrQualityChoices : []}AppButton {- text: "Reset"+ text: qsTranslate("App", "Reset")iconName: "reset"width: (parent.width - 16) / 3buttonHeight: 30@@ -453,7 +464,7 @@ model: appBridge ? appBridge.vsrQualityChoices : []}AppButton {- text: "Outputs"+ text: qsTranslate("App", "Outputs")iconName: "outputs_folder"width: (parent.width - 16) / 3buttonHeight: 30@@ -467,7 +478,7 @@ model: appBridge ? appBridge.vsrQualityChoices : []visible: !root.isImageAppButton {- text: "Preview"+ text: qsTranslate("App", "Preview")iconName: "preview"width: Math.max(100, parent.width - 156)buttonHeight: 30@@ -487,20 +498,20 @@ model: appBridge ? appBridge.vsrQualityChoices : []AppIconButton {iconName: "reset"buttonSize: 30- tooltipText: "Reset upscale settings"+ tooltipText: qsTranslate("App", "Reset upscale settings")onClicked: { if (appBridge) appBridge.resetTabSettings("upscale") }}AppIconButton {iconName: "outputs_folder"buttonSize: 30- tooltipText: "Open outputs folder"+ tooltipText: qsTranslate("App", "Open outputs folder")onClicked: { if (appBridge) appBridge.openFolder("") }}}AppButton {- text: appBridge && appBridge.canStop ? "Stop" : (root.isImage ? "Upscale Image(s)" : "Upscale Video(s)")+ text: appBridge && appBridge.canStop ? qsTranslate("App", "Stop") : (root.isImage ? qsTranslate("App", "Upscale Image(s)") : qsTranslate("App", "Upscale Video(s)"))iconName: appBridge && appBridge.canStop ? "stop" : "start_render"variant: appBridge && appBridge.canStop ? "danger" : "primary"width: parent.widthdiff --git a/src/desktop/reference_color.py b/src/desktop/reference_color.pynew file mode 100644index 0000000..8392f70--- /dev/null+++ b/src/desktop/reference_color.py@@ -0,0 +1,227 @@+"""Fit editable grading controls to an image's perceptual color distribution.++Only bounded floating-point samples are analyzed here. Full-resolution+rendering uses the existing Vulkan LUT pipeline; no image-specific pixel+transform is hidden outside the visible sliders or exported cube.+"""+from __future__ import annotations++import math+from dataclasses import replace+from pathlib import Path++import numpy as np++from ..neural_rendering.image.decoder import decode_image+from ..settings.models import LUT_ADJUSTMENT_RANGES, UISettings+from .auto_color import _analysis_pixels, _check_cancel, _source_pixels+from .coloring import grade_lut_rgb, load_cube_lut, sample_cube_lut+++_KEYS = tuple(key for key in LUT_ADJUSTMENT_RANGES if key != "lut_mix")+_SCALES = np.asarray([1.0 if key == "lut_exposure" else+ 90.0 if key == "lut_hue" else 100.0 for key in _KEYS])+_LOW = np.asarray([LUT_ADJUSTMENT_RANGES[key][0] for key in _KEYS]) / _SCALES+_HIGH = np.asarray([LUT_ADJUSTMENT_RANGES[key][1] for key in _KEYS]) / _SCALES+_QUANTILES = np.asarray((.005, .01, .025, .05, .10, .15, .20, .25, .30,+ .35, .40, .45, .50, .55, .60, .65, .70, .75,+ .80, .85, .90, .95, .975, .99, .995))+_DIRECTIONS = np.asarray((+ (1, 0, 0), (0, 1, 0), (0, 0, 1), (0, 1, 1), (0, 1, -1),+ (1, 1, 0), (1, -1, 0), (1, 0, 1), (1, 0, -1),+ (1, 1, 1), (1, 1, -1), (1, -1, 1), (1, -1, -1),+), dtype=np.float32)+_DIRECTIONS /= np.linalg.norm(_DIRECTIONS, axis=1, keepdims=True)+++def _oklab(rgb: np.ndarray) -> np.ndarray:+ # Bjorn Ottosson's public-domain linear-sRGB -> Oklab conversion:+ # https://bottosson.github.io/posts/oklab/#converting-from-linear-srgb-to-oklab+ linear = np.where(rgb <= .04045, rgb / 12.92, ((rgb + .055) / 1.055) ** 2.4)+ r, g, b = linear.T+ l = np.cbrt(.4122214708 * r + .5363325363 * g + .0514459929 * b)+ m = np.cbrt(.2119034982 * r + .6806995451 * g + .1073969566 * b)+ s = np.cbrt(.0883024619 * r + .2817188376 * g + .6299787005 * b)+ return np.column_stack((.2104542553 * l + .7936177850 * m - .0040720468 * s,+ 1.9779984951 * l - 2.4285922050 * m + .4505937099 * s,+ .0259040371 * l + .7827717662 * m - .8086757660 * s))+++def _features(rgb: np.ndarray) -> np.ndarray:+ # Joint projections distinguish warm/cool shadows and highlight casts;+ # matching each RGB histogram independently would lose that relationship.+ lab = _oklab(rgb)+ lab[:, 1:] *= 1.6+ projections = lab @ _DIRECTIONS.T+ distributions = np.quantile(projections, _QUANTILES, axis=0).ravel()+ chroma = np.quantile(np.linalg.norm(lab[:, 1:], axis=1), _QUANTILES)+ return np.concatenate((distributions, chroma))+++def _sample(pixels: np.ndarray, size: int) -> np.ndarray:+ if len(pixels) > size:+ pixels = pixels[np.linspace(0, len(pixels) - 1, size, dtype=np.intp)]+ return np.ascontiguousarray(pixels, dtype=np.float32)+++def _valid_pixels(pixels: np.ndarray) -> np.ndarray:+ pixels = np.asarray(pixels, dtype=np.float32)+ if pixels.ndim != 2 or pixels.shape[1] != 3:+ raise ValueError("Reference matching requires RGB color samples.")+ pixels = pixels[np.all(np.isfinite(pixels), axis=1)]+ if len(pixels) < 32:+ raise ValueError("The input or reference has too few visible colors to analyze.")+ return np.clip(pixels, 0.0, 1.0)+++def _controls(vector: np.ndarray, *, quantize: bool = False) -> dict[str, int | float]:+ values = np.clip(vector, _LOW, _HIGH) * _SCALES+ return {key: (round(float(value), 2) if key == "lut_exposure" else int(round(value)))+ if quantize else float(value) for key, value in zip(_KEYS, values)}+++def _fit(identity, sampled, reference, settings, initial, iterations, controller, report):+ target = _features(reference)+ weight = 1.0 / math.sqrt(len(target))+ low, high = _LOW.copy(), _HIGH.copy()++ def residual(vector):+ _check_cancel(controller)+ graded = grade_lut_rgb(identity, sampled, replace(settings, **_controls(vector)))+ # A small preference for gentle controls resolves exposure/midtones+ # and saturation/vibrance ambiguities without overriding the target.+ return np.concatenate(((_features(graded) - target) * weight,+ vector * .00035))++ vector = np.clip(initial, low, high)+ error = residual(vector)+ score = float(error @ error)+ damping = .0001+ for iteration in range(iterations):+ _check_cancel(controller)+ jacobian = np.empty((len(error), len(vector)))+ for column in range(len(vector)):+ step = .002 if vector[column] + .002 <= high[column] else -.002+ trial = vector.copy()+ trial[column] += step+ jacobian[:, column] = (residual(trial) - error) / step+ normal = jacobian.T @ jacobian+ gradient = jacobian.T @ error+ accepted = False+ improvement = 0.0+ for _ in range(7):+ delta = np.linalg.solve(normal + np.eye(len(vector)) * damping, -gradient)+ delta = np.clip(delta, -.35, .35)+ candidate = np.clip(vector + delta, low, high)+ candidate_error = residual(candidate)+ candidate_score = float(candidate_error @ candidate_error)+ if candidate_score < score:+ improvement = score - candidate_score+ vector, error, score = candidate, candidate_error, candidate_score+ damping = max(.00000001, damping * .4)+ accepted = True+ break+ damping *= 4.0+ if report is not None:+ report((iteration + 1) / iterations)+ if not accepted or (iteration > 4 and improvement < 1e-10):+ break+ return vector, score+++def match_reference_adjustments(identity: np.ndarray, sampled: np.ndarray,+ reference: np.ndarray, settings: UISettings, *,+ controller=None, progress=None) -> dict[str, int | float]:+ """Fit tone, white balance, hue, and saturation; preserve mix/resolution."""+ if settings.lut_mix <= 0:+ raise ValueError("Increase LUT Strength above 0 before matching a reference image.")+ identity, sampled = (np.asarray(pixels, dtype=np.float32) for pixels in (identity, sampled))+ if identity.shape != sampled.shape or identity.ndim != 2 or identity.shape[1] != 3:+ raise ValueError("Source and LUT samples must describe the same colors.")+ valid = np.all(np.isfinite(identity) & np.isfinite(sampled), axis=1)+ identity, sampled, reference = (_valid_pixels(identity[valid]), _valid_pixels(sampled[valid]),+ _valid_pixels(reference))+ _check_cancel(controller)+ coarse_identity, coarse_sampled, coarse_reference = (+ _sample(pixels, 2048) for pixels in (identity, sampled, reference))+ current = np.asarray([getattr(settings, key) for key in _KEYS]) / _SCALES+ neutral = np.zeros(len(_KEYS))+ seeds = [neutral, current]+ # Exposure initialization helps very dark/bright sources reach the target+ # before the finer contrast, tone zones, and color controls are fitted.+ guessed = neutral.copy()+ source_level = max(float(np.median(_oklab(coarse_sampled)[:, 0])), .03)+ target_level = max(float(np.median(_oklab(coarse_reference)[:, 0])), .03)+ guessed[0] = np.clip(3 * math.log2(target_level / source_level), -3, 3)+ seeds.append(guessed)+ best, best_score = neutral, float("inf")+ unique = []+ for seed in seeds:+ if not any(np.allclose(seed, previous) for previous in unique):+ unique.append(seed)+ for index, seed in enumerate(unique):+ def report(value, i=index):+ if progress is not None:+ progress(.20 + .40 * (i + value) / len(unique), "Matching reference tone and color")+ fitted, score = _fit(coarse_identity, coarse_sampled, coarse_reference,+ settings, seed, 35, controller, report)+ if score < best_score:+ best, best_score = fitted, score++ fine_identity, fine_sampled, fine_reference = (+ _sample(pixels, 12_288) for pixels in (identity, sampled, reference))+ best, _ = _fit(fine_identity, fine_sampled, fine_reference, settings, best, 45,+ controller, lambda value: progress(.60 + .35 * value, "Refining reference match")+ if progress is not None else None)+ # Refine at the actual integer slider precision, rather than returning a+ # continuous optimum that can lose its accuracy when displayed/applied.+ values = _controls(best, quantize=True)+ target = _features(fine_reference)+ def score(values):+ _check_cancel(controller)+ difference = _features(grade_lut_rgb(fine_identity, fine_sampled,+ replace(settings, **values))) - target+ return float(difference @ difference)+ best_score = score(values)+ for _ in range(2):+ for key in _KEYS:+ step = .01 if key == "lut_exposure" else 1+ low, high = LUT_ADJUSTMENT_RANGES[key]+ for direction in (-1, 1):+ candidate = {**values, key: round(float(values[key]) + direction * step, 2)+ if key == "lut_exposure" else int(values[key]) + direction}+ if low <= candidate[key] <= high:+ candidate_score = score(candidate)+ if candidate_score < best_score:+ values, best_score = candidate, candidate_score+ _check_cancel(controller)+ if progress is not None:+ progress(1.0, "Reference color adjustments ready")+ return values+++def analyze_color_reference(source: str | Path, reference: str | Path,+ settings: UISettings, mode: str, *,+ duration_seconds: float = 0.0,+ video_size: tuple[int, int] | None = None,+ hdr: bool = False, controller=None, progress=None) -> dict[str, int | float]:+ """Analyze the source and a decoded reference, then fit the editable grade."""+ del hdr # Match the signal consumed by the existing grading controls.+ pixels = _source_pixels(Path(source).resolve(), mode, duration_seconds, video_size,+ controller, lambda value, message: progress(.12 * value, message)+ if progress is not None else None)+ _check_cancel(controller)+ if progress is not None:+ progress(.14, "Analyzing reference image")+ reference_pixels = _analysis_pixels(decode_image(Path(reference).resolve()).rgba, 220_000)+ _check_cancel(controller)+ sampled = pixels+ if settings.lut_path:+ lut = load_cube_lut(settings.lut_path)+ sampled = np.empty_like(pixels)+ for offset in range(0, len(pixels), 65_536):+ _check_cancel(controller)+ end = min(len(pixels), offset + 65_536)+ sampled[offset:end] = sample_cube_lut(pixels[offset:end], lut)+ return match_reference_adjustments(pixels, sampled, reference_pixels, settings,+ controller=controller, progress=progress)diff --git a/src/desktop/rolling_workflow.py b/src/desktop/rolling_workflow.pynew file mode 100644index 0000000..d7d1e0f--- /dev/null+++ b/src/desktop/rolling_workflow.py@@ -0,0 +1,696 @@+"""Continuous video stages, a bounded encoded spool and one delivery encoder.++GPU sessions and the interpolation timeline live for the entire source. Only+the first stage is spooled; later stages exchange frames through bounded pipes,+so a high-FPS or upscaled later stage cannot create a second full-video cache.+"""+from __future__ import annotations++import itertools+import math+import subprocess+import threading+import time+from collections import deque+from contextlib import ExitStack, suppress+from dataclasses import dataclass, replace+from fractions import Fraction+from pathlib import Path++import av+import numpy as np++from ..core import app_log, ffmpeg+from ..core.disk_paths import OutputFile+from ..core.ffmpeg.audio import plan_audio_streams+from ..core.ffmpeg.encoder import _codec_command+from ..core.ffmpeg.filters import scaling_filter+from ..core.ffmpeg.frames import _Reader, open_video_decoder, packed_frame+from ..core.ffmpeg.nut import RawVideoPacketMuxer+from ..core.ffmpeg.sharpening import sharpening_filter+from ..core.ffmpeg.vulkan import prepare_command+from ..core.jobs import BoundedLogBuffer, Cancelled, active_job, drain_bounded_text+from ..core.paths import FFMPEG+from ..core.rolling_cache import CACHE_BYTES, RollingFrameCache+from ..core.runtime import resolve_output_size+from ..frame_interpolation.models import resolve_target_rate+from ..settings.models import UISettings+from .coloring import has_lut_adjustments, load_cube_lut, save_cube_lut+++FILTER_STAGES = {"coloring", "scale_method", "cas_sharpening"}+++class _Cancellation:+ def __init__(self, owner, stop):+ self.owner, self.stop = owner, stop++ def is_set(self):+ return self.stop.is_set() or self.owner.is_set()+++class _Control:+ def __init__(self, owner):+ self.owner = owner+ self.stop = threading.Event()+ self.cancel = _Cancellation(owner.cancel, self.stop)++ def __getattr__(self, name):+ return getattr(self.owner, name)++ def check(self):+ if self.cancel.is_set():+ raise Cancelled("Video processing stopped.")+++@dataclass(frozen=True)+class VideoState:+ width: int+ height: int+ rate: Fraction+ depth: int+ hdr: bool+ metadata: dict++ @classmethod+ def from_metadata(cls, meta):+ return cls(int(meta["width"]), int(meta["height"]), Fraction(meta["rate"]),+ int(meta["depth"]), bool(meta["hdr"]), dict(meta))++ def rgb(self, *, width=None, height=None, rate=None, hdr=None):+ hdr = self.hdr if hdr is None else hdr+ width, height = width or self.width, height or self.height+ rate = rate or self.rate+ meta = {**self.metadata, "width": width, "height": height, "rate": rate,+ "fps": float(rate), "depth": 10, "hdr": hdr, "rotation": 0,+ "pixel_format": "gbrp10le", "color_space": "gbr", "color_range": "pc"}+ if hdr != self.hdr:+ meta.update(color_primaries="bt2020", color_transfer="smpte2084")+ return VideoState(width, height, rate, 10, hdr, meta)+++def filter_groups(stages):+ groups = []+ for stage in stages:+ if stage in FILTER_STAGES and groups and isinstance(groups[-1], tuple):+ groups[-1] += (stage,)+ else:+ groups.append((stage,) if stage in FILTER_STAGES else stage)+ return groups+++def build_filter_group(stages, state, settings, directory, controller):+ filters = []+ for stage in stages:+ if stage == "scale_method":+ w, h = resolve_output_size(state.width, state.height, settings.upscaling_factor)+ filters.append(scaling_filter(w, h, settings.video_scaling_filter))+ state = state.rgb(width=w, height=h)+ elif stage == "coloring":+ lut = directory / "reference.cube"+ if settings.lut_path and not has_lut_adjustments(settings):+ import shutil+ shutil.copyfile(settings.lut_path, lut)+ else:+ save_cube_lut(lut, settings.lut_path or None, settings, controller=controller)+ load_cube_lut(lut)+ filters.append("libplacebo=lut=reference.cube:lut_type=native:deband=0:dithering=-1:format=gbrp10le")+ state = state.rgb()+ elif stage == "cas_sharpening":+ if settings.cas_sharpness:+ transfer = {"iec61966-2-1": "srgb", "linear": "linear"}.get(+ state.metadata.get("color_transfer"), "bt709")+ filters.append(sharpening_filter(settings.sharpening_method, settings.cas_sharpness, transfer))+ state = state.rgb()+ # Preserve the same 10-bit boundary as the original FFV1 workflow,+ # without writing and decoding a checkpoint at every card.+ filters.append("format=gbrp10le")+ return "ve_gpu," + ",".join(filters), state+++def _timing(frame, original):+ frame.pts, frame.time_base, frame.duration = original.pts, original.time_base, original.duration+ return frame+++def _color_tags(meta, *, rgb=True):+ primary = meta.get("color_primaries")+ transfer = meta.get("color_transfer")+ primary = primary if primary not in {None, "", "unknown", "unspecified"} else "bt2020" if meta.get("hdr") else "bt709"+ transfer = transfer if transfer not in {None, "", "unknown", "unspecified"} else "smpte2084" if meta.get("hdr") else "bt709"+ matrix = "gbr" if rgb else meta.get("color_space", "bt709")+ if matrix in {"unknown", "unspecified", None, ""}:+ matrix = "bt2020nc" if meta.get("hdr") else "bt709"+ return f"setparams=colorspace={matrix}:range={'full' if rgb else 'limited'}:color_primaries={primary}:color_trc={transfer}"+++def _close_process(process, controller, log_thread=None):+ if process.poll() is None:+ process.kill()+ process.wait(timeout=10)+ controller.unregister(process)+ if log_thread:+ log_thread.join(timeout=2)+ for pipe in (process.stdin, process.stdout, process.stderr):+ if pipe:+ with suppress(OSError):+ pipe.close()+++def pipe_filter(frames, before, after, graph, controller, directory, *, pixel_format="gbrp10le", tag_output=True):+ """Persistent CLI filter; the input writer and output reader run together."""+ frames = iter(frames)+ first = next(frames)+ tags = _color_tags(before.metadata, rgb=first.format.is_rgb)+ colors = ["-color_primaries", "bt2020" if after.hdr else str(after.metadata.get("color_primaries") or "bt709"),+ "-color_trc", "smpte2084" if after.hdr else str(after.metadata.get("color_transfer") or "bt709")]+ for i in (1, 3):+ if colors[i] in {"unknown", "unspecified"}:+ colors[i] = "bt709"+ if not tag_output:+ colors = []+ command = [str(FFMPEG), "-v", "warning", "-xerror", "-copyts", "-probesize", "32", "-analyzeduration", "0",+ "-f", "nut", "-i", "pipe:0", "-map", "0:v:0", "-an",+ "-vf", tags + "," + graph, "-c:v", "rawvideo", "-pix_fmt", pixel_format,+ *colors, "-fps_mode", "passthrough", "-enc_time_base", "demux",+ "-f", "nut", "-write_index", "0", "-flush_packets", "1", "pipe:1"]+ command = prepare_command(command, selection=controller.ffmpeg_device,+ dimensions=(after.width, after.height), input_format=first.format.name,+ rate=str(before.rate), time_base=str(first.time_base))+ process = subprocess.Popen(command, cwd=directory, stdin=subprocess.PIPE, stdout=subprocess.PIPE,+ stderr=subprocess.PIPE, creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))+ controller.register(process)+ logs = BoundedLogBuffer(max_tail=60)+ logger = threading.Thread(target=drain_bounded_text, args=(process.stderr, logs), daemon=True)+ logger.start()+ failure = []+ written = [0]++ def write():+ muxer = None+ try:+ muxer = RawVideoPacketMuxer(process.stdin, width=first.width, height=first.height,+ rate=before.rate, time_base=first.time_base, pix_fmt=first.format.name)+ for frame in itertools.chain((first,), frames):+ controller.check()+ if (frame.width, frame.height, frame.format.name) != (first.width, first.height, first.format.name):+ raise ValueError("Filter input dimensions or sample format changed.")+ pts = round(Fraction(frame.pts) * frame.time_base / muxer.time_base)+ duration = round(Fraction(frame.duration or 0) * frame.time_base / muxer.time_base)+ muxer.write(packed_frame(frame), pts, duration)+ written[0] += 1+ muxer.close()+ muxer = None+ process.stdin.close()+ except BaseException as exc:+ failure.append(exc)+ if process.poll() is None:+ process.kill()+ finally:+ if muxer:+ with suppress(Exception):+ muxer.close()+ close = getattr(frames, "close", None)+ if close:+ close()++ writer = threading.Thread(target=write, name="rolling-filter-input", daemon=True)+ writer.start()+ container = None+ read = 0+ complete = False+ try:+ container = av.open(_Reader(process.stdout), format="nut")+ for frame in container.decode(video=0):+ controller.check()+ if frame.is_corrupt:+ raise RuntimeError("A processing filter produced a corrupt frame.")+ read += 1+ yield frame+ writer.join(timeout=30)+ if writer.is_alive():+ raise RuntimeError("Processing filter input did not finish.")+ if failure:+ raise failure[0]+ process.wait(timeout=30)+ logger.join(timeout=2)+ if process.returncode:+ raise RuntimeError("Video filter failed:\n" + "\n".join(logs.snapshot()))+ if read != written[0]:+ raise RuntimeError(f"Video filter emitted {read} frames for {written[0]} inputs.")+ complete = True+ except (av.error.FFmpegError, OSError) as exc:+ logger.join(timeout=1)+ if failure:+ raise failure[0] from exc+ raise RuntimeError("Video filter failed:\n" + "\n".join(logs.snapshot())) from exc+ finally:+ if not complete:+ controller.stop.set()+ controller.terminate_processes()+ _close_process(process, controller, logger)+ writer.join(timeout=30)+ if container:+ container.close()+++def source_frames(source, state, controller, stats, *, pixel_format=None, video_filter=None, directory=None):+ rotation = int(state.metadata.get("rotation") or 0)+ graph = {90: "transpose=clock", 180: "hflip,vflip", 270: "transpose=cclock"}.get(rotation, "")+ if video_filter is not None:+ graph = video_filter+ origin = last = None+ count = 0+ with open_video_decoder(source, controller, pixel_format=pixel_format, video_filter=graph, cwd=directory) as decoder:+ for frame in decoder.decode(video=0):+ controller.check()+ if frame.is_corrupt:+ raise RuntimeError("Source decoder returned a corrupt frame.")+ tb = frame.time_base or state.metadata["time_base"]+ stamp = Fraction(frame.pts) * tb if frame.pts is not None else Fraction(count, 1) / state.rate+ if origin is None:+ origin = stamp+ stamp -= origin+ if last is not None and stamp <= last:+ raise ValueError("Source video has non-increasing presentation timestamps.")+ frame.pts = round(stamp / tb)+ frame.time_base = tb+ if not frame.duration:+ frame.duration = max(1, round(Fraction(1, 1) / state.rate / tb))+ last = stamp+ count += 1+ stats["source_frames"] = count+ stats["duration"] = stamp + Fraction(frame.duration) * tb+ yield frame+ declared = int(state.metadata.get("frames") or 0)+ if not count or (declared and declared != count):+ raise RuntimeError(f"Decoded {count} source frames; metadata declares {declared}.")+++def neural_frames(frames, state, settings, controller):+ from ..core.gpu_selection import resolve_runtime_ai_gpu+ from ..core.runtime import DLSSFrameSession, prepare_runtime, resize_fit, resolve_native_settings, resolve_upscaling_mode+ from ..neural_rendering.video.guides import TemporalGuideGenerator+ from .workflow import _neural_video_options+ prepared = prepare_runtime()+ gpu = resolve_runtime_ai_gpu(prepared.gpus, prepared.runtime_bundle, settings.ai_gpu_uuid)+ opts = _neural_video_options(settings, state.hdr)+ factor, mode = resolve_upscaling_mode(1.0)+ session = DLSSFrameSession(input_width=state.width, input_height=state.height,+ output_width=state.width, output_height=state.height,+ frame_count=None, warmup_frames=opts.warmup_frames, factor=factor, mode=mode,+ native_settings=resolve_native_settings(opts), composition_mask=opts.nr_mask,+ gpu=gpu, runtime_bundle=prepared.runtime_bundle, controller=controller)+ guides = TemporalGuideGenerator(session.render_width, session.render_height)+ try:+ for index, frame in enumerate(frames):+ controller.check()+ rgba = ffmpeg.decoded_rgba(frame, state.depth)+ if rgba.shape[:2] != (session.render_height, session.render_width):+ rgba = resize_fit(rgba, session.render_width, session.render_height, controller=controller)+ guide = guides.process(rgba)+ processed, _ = session.process(index=index, rgba=np.ascontiguousarray(rgba),+ reset=guide.reset, pts=frame.pts)+ yield _timing(av.VideoFrame.from_ndarray(processed, format="rgba64le" if processed.dtype == np.uint16 else "rgba"), frame)+ finally:+ session.close()+++def dlss_frames(frames, state, settings, controller):+ from ..core.dlss_bridge import DLSSSession+ from ..neural_rendering.video.guides import TemporalGuideGenerator+ session = DLSSSession(state.width, state.height, settings.upscale_dlss_mode, settings.upscale_dlss_preset,+ gpu_uuid=settings.ai_gpu_uuid, even=True)+ guides = TemporalGuideGenerator(state.width, state.height, cut_threshold=.10)+ try:+ for index, frame in enumerate(frames):+ controller.check()+ rgba = np.ascontiguousarray(ffmpeg.decoded_rgba(frame, state.depth))+ guide = guides.process(rgba)+ result = session.process(rgba, reset=guide.reset, phase=index)+ pixels = np.rint(np.clip(result.astype(np.float32), 0, 1) * 65535).astype(np.uint16)+ pixels[..., 3] = 65535+ yield _timing(av.VideoFrame.from_ndarray(pixels, format="rgba64le"), frame)+ finally:+ session.close()+++def rtx_frames(frames, state, after, settings, stage, controller, directory, *, normalized_input=False):+ from ..upscale.video.host_pipeline import _PinnedFramePool+ from ..upscale.video.media import packed_bytes, sdr_normalization_filter+ from ..upscale.video.native import RTXVideoSession, FORMAT_R10, FORMAT_RGBA8, FORMAT_YUV422P10, probe_capabilities+ from .workflow import _video_upscale_stage_options+ opts = _video_upscale_stage_options(settings, stage)+ caps = probe_capabilities(settings.ai_gpu_uuid, controller=controller)+ fmt = "gbrp10le" if state.depth > 8 else "rgba"+ # RTX Video accepts gamma-2.2 BT.709 RGB, matching the existing host path.+ primary = state.metadata.get("color_primaries") or "bt709"+ transfer = state.metadata.get("color_transfer") or "bt709"+ primary = "bt709" if primary in {"unknown", "unspecified"} else primary+ transfer = "bt709" if transfer in {"unknown", "unspecified"} else transfer+ source_format = av.VideoFormat(state.metadata.get("pixel_format") or "gbrp10le")+ matrix = "gbr" if source_format.is_rgb else state.metadata.get("color_space")+ if matrix in {None, "", "unknown", "unspecified"}:+ matrix = "bt470bg" if state.height == 576 else "smpte170m" if state.height < 576 else "bt709"+ range_in = "full" if source_format.is_rgb or state.metadata.get("color_range") == "pc" else "limited"+ planar = "gbrp10le" if state.depth > 8 else "gbrp"+ graph = f"ve_gpu,{sdr_normalization_filter(matrix, primary, transfer, range_in)},format={planar},scale={state.width}:{state.height}:flags=lanczos,setsar=1,format={fmt}"+ gamma = replace(state, metadata={**state.metadata, "color_primaries": "bt709", "color_transfer": "bt470m"})+ normalized = (iter(frames) if normalized_input else+ pipe_filter(frames, state, gamma, graph, controller, directory, pixel_format=fmt, tag_output=False))+ session = RTXVideoSession(state.width, state.height, after.width, after.height, opts,+ FORMAT_R10 if state.depth > 8 else FORMAT_RGBA8, caps, controller)+ pool = None+ try:+ pool = _PinnedFramePool(int(caps.gpu["cuda_ordinal"]), after.width, after.height,+ FORMAT_YUV422P10, "yuv422p10le", controller, capacity=1)+ for frame in normalized:+ controller.check()+ slot = pool.acquire()+ try:+ session.process_host_to_host_planar(packed_bytes(frame), output_format=FORMAT_YUV422P10,+ plane_pointers=slot.plane_pointers, strides=slot.strides)+ slot.pts, slot.time_base, slot.duration = frame.pts, frame.time_base, frame.duration+ result, _ = slot.to_av_frame()+ finally:+ slot.release()+ result.colorspace, result.color_range = (9 if after.hdr else 1), 1+ result.color_primaries, result.color_trc = (9, 16) if after.hdr else (1, 1)+ yield result+ finally:+ normalized.close()+ if pool:+ pool.close(abort=controller.cancel.is_set())+ session.close()+++def interpolation_frames(frames, state, settings, controller, directory):+ from ..core.gpu_selection import detect_gpu+ from ..frame_interpolation.capabilities import probe_frame_interpolation_capabilities+ from ..frame_interpolation.native import DirectDLSSGSession, DLSSGCudaSurface+ from ..frame_interpolation.processor import (DLSSGStage, NearestTimestampWriter, TimedFrame,+ _matrix_code, _primaries_code, _range_code, _transfer_code)+ from ..frame_interpolation.scheduler import choose_interpolation_plan, output_frame_count+ target = resolve_target_rate(settings.frame_interpolation_target_fps)+ caps = probe_frame_interpolation_capabilities(settings.ai_gpu_uuid)+ plan = choose_interpolation_plan(state.rate, target, settings.frame_interpolation_engine,+ caps.native_multiplier, cfr=bool(state.metadata.get("cfr", True)))+ count = 1 if plan.path == "Native DLSSG" else plan.cascade_stages+ generated = plan.generated_per_interval if plan.path == "Native DLSSG" else 1+ ordinal = int(detect_gpu(settings.ai_gpu_uuid)["cuda_ordinal"])+ colors = {"color_matrix": _matrix_code(state.metadata, hdr=state.hdr),+ "color_range": _range_code(state.metadata), "color_primaries": _primaries_code(state.metadata),+ "color_transfer": _transfer_code(state.metadata), "rotation": 0}+ if state.hdr:+ yuv = replace(state, metadata={**state.metadata, "color_space": "bt2020nc", "color_range": "tv"})+ frames = pipe_filter(frames, state, yuv, "ve_gpu,format=p010le", controller, directory, pixel_format="p010le")+ colors["color_matrix"], colors["color_range"] = 2, 0+ sessions = []+ stages = []+ ready = deque()++ def emit(selected, index):+ pixels = selected.encode_frame+ if isinstance(pixels, DLSSGCudaSurface):+ pixels = pixels.to_host_rgb()+ if state.hdr:+ rgb = np.rint(np.clip(pixels[..., :3].astype(np.float32), 0, 1) * 1023).astype(np.uint16)+ pixels = av.VideoFrame.from_ndarray(np.ascontiguousarray(rgb[..., [1, 2, 0]]), format="gbrp10le")+ else:+ pixels = av.VideoFrame.from_ndarray(pixels, format="rgba")+ elif isinstance(pixels, np.ndarray):+ pixels = av.VideoFrame.from_ndarray(pixels, format="rgba")+ # A selected source frame can be emitted more than once; give each its+ # own header so assigning the new PTS never mutates temporal history.+ copied = av.VideoFrame(pixels.width, pixels.height, pixels.format.name)+ for dst, src in zip(copied.planes, pixels.planes):+ if dst.line_size == src.line_size:+ dst.update(src)+ else:+ source = np.frombuffer(src, dtype=np.uint8).reshape(src.height, src.line_size)+ target_data = np.zeros((dst.height, dst.line_size), dtype=np.uint8)+ row = min(src.line_size, dst.line_size)+ target_data[:, :row] = source[:, :row]+ dst.update(target_data)+ copied.pts, copied.time_base, copied.duration = index, Fraction(1, 1) / target, 1+ ready.append(copied)++ # Online nearest-timestamp resampling. The true output count is determined+ # at source EOF rather than decoding the whole video in a preflight scan.+ writer = NearestTimestampWriter(target, 2**63 - 1, emit)+ last = None+ segment = 0+ end = Fraction(0)+ try:+ for i in range(count):+ session = DirectDLSSGSession(state.width, state.height, generated, controller, ordinal, hdr=state.hdr)+ sessions.append(session)+ stages.append(DLSSGStage(session, generated, detect_source_cuts=i == 0,+ cuda_output=False, output_p010=state.hdr, colors=colors,+ preserve_source_rgb=i == 0))+ for index, frame in enumerate(frames):+ controller.check()+ stamp = Fraction(frame.pts) * frame.time_base+ if last is not None and (stamp <= last or stamp - last > Fraction(2, 1) / state.rate):+ segment += 1+ last = stamp+ end = stamp + (Fraction(frame.duration) * frame.time_base if frame.duration else Fraction(1, 1) / state.rate)+ bridge = frame if state.hdr else np.ascontiguousarray(frame.to_ndarray(format="rgba"))+ items = [TimedFrame(bridge, frame, stamp, segment, "Source", index)]+ for stage in stages:+ items = [produced for item in items for produced in stage.push(item)]+ for item in items:+ writer.push(item)+ while ready:+ yield ready.popleft()+ del frame, items+ if bool(state.metadata.get("cfr", True)) and last is not None:+ # Matroska's millisecond PTS/duration rounding can make an 18-frame+ # 30-FPS clip look like .601 s. Its CFR duration is exactly .600 s;+ # otherwise ceil(duration * target) introduces an extra last frame.+ end = Fraction(index + 1, 1) / state.rate+ writer.output_count = output_frame_count(end, target)+ writer.finish()+ while ready:+ yield ready.popleft()+ finally:+ ready.clear()+ for session in reversed(sessions):+ session.close()+ close = getattr(frames, "close", None)+ if close:+ close()+++def native_stage(stage, frames, state, settings, controller, directory, *, normalized_input=False):+ from .workflow import _video_upscale_stage_options, video_upscale_size+ after = state.rgb()+ if stage == "neural_model":+ transformed = neural_frames(frames, state, settings, controller)+ elif stage == "dlss_super_resolution":+ from ..core.dlss_modes import dlss_output_size+ w, h = dlss_output_size(state.width, state.height, settings.upscale_dlss_mode, even=True)+ after = state.rgb(width=w, height=h)+ transformed = dlss_frames(frames, state, settings, controller)+ elif stage in {"super_resolution", "rtx_video_hdr"}:+ w, h, _ = video_upscale_size(state.width, state.height, _video_upscale_stage_options(settings, stage))+ after = state.rgb(width=w, height=h, hdr=stage == "rtx_video_hdr")+ transformed = rtx_frames(frames, state, after, settings, stage, controller, directory,+ normalized_input=normalized_input)+ elif stage == "frame_generation":+ after = state.rgb(rate=resolve_target_rate(settings.frame_interpolation_target_fps))+ transformed = interpolation_frames(frames, state, settings, controller, directory)+ else:+ raise ValueError(f"Unknown rolling processing stage: {stage}.")+ # Output packing/clamping matches the existing FFV1 stage boundaries.+ # RTX's bridge returns tagged YUV, other native engines return RGB.+ raw_meta = after.metadata+ if stage in {"super_resolution", "rtx_video_hdr"}:+ raw_meta = {**raw_meta, "color_space": "bt2020nc" if after.hdr else "bt709", "color_range": "tv"}+ raw = replace(after, metadata=raw_meta)+ return pipe_filter(transformed, raw, after, "ve_gpu,format=gbrp10le", controller, directory), after+++def _encode(frames, state, source, destination, settings, controller, progress, stats):+ frames = iter(frames)+ first = next(frames)+ output = OutputFile(destination)+ process = muxer = logger = None+ completed = False+ delivered = 0+ meta = dict(state.metadata)+ if settings.codec != "FFV1 Lossless RGB 10-bit":+ meta["color_space"] = "bt2020nc" if state.hdr else stats["source_metadata"].get("color_space")+ if meta["color_space"] in {None, "", "unknown", "gbr"}:+ meta["color_space"] = "bt709"+ meta["color_range"] = "tv"+ gpu = ffmpeg.resolve_video_gpu((), settings.video_gpu_uuid, settings.codec, state.width, state.height)+ codec_args, selected, _ = _codec_command(settings.codec, settings.quality, state.width, state.height,+ float(state.rate), None if gpu is None else int(gpu["cuda_ordinal"]),+ hdr_mode=state.hdr, hdr_metadata=meta)+ audio = plan_audio_streams(source, ffmpeg.resolve_container(settings.codec, settings.container), controller)+ tags = _color_tags(state.metadata, rgb=first.format.is_rgb)+ duration = float(state.metadata.get("video_duration") or state.metadata.get("duration") or 0)+ command = [str(FFMPEG), "-v", "warning", "-xerror", "-y", "-probesize", "32", "-analyzeduration", "0",+ "-f", "nut", "-i", "pipe:0",+ *(["-t", f"{duration:.9f}"] if duration > 0 else []), "-i", str(source),+ "-map", "0:v:0", "-map", "1:a?", "-map_metadata", "1", "-map_chapters", "1",+ "-vf", tags, *codec_args, *audio.encoder_args(), "-fps_mode", "passthrough",+ str(output.temporary)]+ command = prepare_command(command, selection=settings.ffmpeg_device,+ dimensions=(state.width, state.height), input_format=first.format.name,+ rate=str(state.rate), time_base=str(first.time_base))+ logs = BoundedLogBuffer(max_tail=60)+ last_update = 0.0+ expected = max(1, duration * float(state.rate))+ try:+ process = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.DEVNULL,+ stderr=subprocess.PIPE, creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))+ controller.register(process)+ logger = threading.Thread(target=drain_bounded_text, args=(process.stderr, logs), daemon=True)+ logger.start()+ muxer = RawVideoPacketMuxer(process.stdin, width=state.width, height=state.height,+ rate=state.rate, time_base=first.time_base, pix_fmt=first.format.name)+ for frame in itertools.chain((first,), frames):+ controller.check()+ pts = round(Fraction(frame.pts) * frame.time_base / muxer.time_base)+ frame_duration = round(Fraction(frame.duration or 0) * frame.time_base / muxer.time_base)+ muxer.write(packed_frame(frame), pts, frame_duration)+ delivered += 1+ now = time.perf_counter()+ if progress and now - last_update >= .2:+ progress(min(.97, delivered / expected * .97), f"Processing video: {delivered:,} frames")+ last_update = now+ muxer.close()+ muxer = None+ process.stdin.close()+ if progress:+ progress(.98, "Finalizing video")+ while process.poll() is None:+ controller.check()+ try:+ process.wait(timeout=.2)+ except subprocess.TimeoutExpired:+ continue+ logger.join(timeout=2)+ if process.returncode:+ raise RuntimeError("Video export failed:\n" + "\n".join(logs.snapshot()))+ if progress:+ progress(.99, "Verifying output")+ saved = ffmpeg.probe_video(output.temporary, count_mode="packets", controller=controller)+ if (int(saved["frames"]) != delivered or+ (int(saved["width"]), int(saved["height"])) != (state.width, state.height)):+ raise RuntimeError("Rolling output frame count or dimensions do not match the processing pipeline.")+ if state.hdr and (not saved["hdr"] or int(saved["depth"]) < 10):+ raise RuntimeError("Rolling output lost HDR signaling or precision.")+ controller.check()+ output.publish()+ stats.update(output_frames=delivered, encoder=selected)+ completed = True+ except (BrokenPipeError, OSError) as exc:+ if logger:+ logger.join(timeout=1)+ raise RuntimeError("Video export failed:\n" + "\n".join(logs.snapshot())) from exc+ finally:+ if not completed:+ controller.stop.set()+ controller.terminate_processes()+ if muxer:+ with suppress(Exception):+ muxer.close()+ if process:+ _close_process(process, controller, logger)+ output.cleanup()+ close = getattr(frames, "close", None)+ if close:+ close()+++def render_rolling_video(source: Path, settings: UISettings, destination: Path,+ controller, directory: Path, stages, progress=None, *, cache_limit=CACHE_BYTES):+ from .workflow import _export_video+ started = time.perf_counter()+ control = _Control(controller)+ meta = ffmpeg.probe_video(source, count_mode="metadata", controller=controller,+ inspect_timestamps="frame_generation" in stages)+ state = VideoState.from_metadata(meta)+ groups = filter_groups(stages)+ def direct_progress(value, message):+ if progress:+ progress(min(.99, float(value)), message)+ # Stateless-only workflows can be delivered in one CLI pass. No cache or+ # extra decode is useful here, even when the user enables rolling mode.+ if len(groups) == 1 and isinstance(groups[0], tuple):+ graph, after = build_filter_group(groups[0], state, settings, directory, controller)+ _export_video(source, source, destination, settings, controller, pipeline_hdr=after.hdr,+ progress=direct_progress, video_filter=graph, output_metadata=after.metadata,+ working_directory=directory, verify_output=True)+ app_log.info("rolling-cache", f"direct src={source.name} elapsed={time.perf_counter()-started:.3f}s cache=0")+ if progress:+ progress(1.0, "Export complete")+ return str(destination)+ if not groups:+ _export_video(source, source, destination, settings, controller, pipeline_hdr=state.hdr,+ progress=direct_progress, verify_output=True)+ if progress:+ progress(1.0, "Export complete")+ return str(destination)+ stats = {"source_metadata": meta}+ cache = None+ destination.parent.mkdir(parents=True, exist_ok=True)+ with active_job(controller), ExitStack() as resources:+ first_stage = groups[0]+ decode_format = None+ initial_filter = None+ first_filtered_state = None+ if isinstance(first_stage, tuple):+ initial_filter, first_filtered_state = build_filter_group(first_stage, state, settings, directory, control)+ rotation = int(state.metadata.get("rotation") or 0)+ rotate = {90: "transpose=clock,", 180: "hflip,vflip,", 270: "transpose=cclock,"}.get(rotation, "")+ initial_filter = rotate + initial_filter+ decode_format = "gbrp10le"+ elif first_stage in ("super_resolution", "rtx_video_hdr"):+ from ..upscale.video.media import inspect_video, decode_filter+ initial_filter, _ = decode_filter(inspect_video(source, control, reject_hdr=True))+ decode_format = "gbrp10le" if state.depth > 8 else "rgba"+ if first_stage in ("neural_model", "dlss_super_resolution"):+ decode_format = "rgba64le" if state.depth > 8 else "rgba"+ elif first_stage == "frame_generation":+ decode_format = "p010le" if state.hdr else "rgba"+ frames = source_frames(source, state, control, stats, pixel_format=decode_format,+ video_filter=initial_filter, directory=directory)+ resources.callback(frames.close)+ try:+ for index, group in enumerate(groups):+ before = state+ if isinstance(group, tuple):+ if index == 0:+ state = first_filtered_state+ else:+ graph, state = build_filter_group(group, state, settings, directory, control)+ frames = pipe_filter(frames, before, state, graph, control, directory)+ else:+ if index == 0 and group in ("super_resolution", "rtx_video_hdr"):+ frames, state = native_stage(group, frames, state, settings, control, directory,+ normalized_input=True)+ else:+ frames, state = native_stage(group, frames, state, settings, control, directory)+ resources.callback(frames.close)+ if index == 0 and len(groups) > 1:+ cache = RollingFrameCache(frames, directory / "rolling-cache", control,+ limit=cache_limit, max_frames=max(1, math.ceil(float(state.rate) * 60)),+ codec=settings.cache_codec)+ resources.callback(cache.close)+ frames = iter(cache)+ resources.callback(frames.close)+ _encode(frames, state, source, destination, settings, control, progress, stats)+ finally:+ control.stop.set()+ controller.terminate_processes()+ app_log.info("rolling-cache", f"done src={source.name} elapsed={time.perf_counter()-started:.3f}s "+ f"source_frames={stats.get('source_frames')} output_frames={stats.get('output_frames')} "+ f"peak_bytes={cache.peak_bytes if cache else 0} limit={cache_limit} "+ f"cache_waits={cache.waits if cache else 0} codec={settings.cache_codec}")+ if progress:+ progress(1.0, "Export complete")+ return str(destination)diff --git a/src/desktop/state.py b/src/desktop/state.pyindex 79e5e10..6bd735b 100644--- a/src/desktop/state.py+++ b/src/desktop/state.py@@ -37,6 +37,7 @@ class PreviewState:input_url: str = ""output_url: str = ""poster_url: str = ""+ preview_error: str = ""input_is_video: bool = Falseoutput_is_video: bool = Falseinput_info: str = ""@@ -60,8 +61,8 @@ class PreviewState:selected_path: str = ""selected_row: int = -1generation: int = 0- # Skip-if-fresh marker for realtime auto-preview: (selected source,- # settings snapshot) captured when the current output preview finished+ # Skip-if-fresh marker for realtime auto-preview: source identity,+ # active settings and timeline frame captured when its 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 = ()diff --git a/src/desktop/translations/app_ar.qm b/src/desktop/translations/app_ar.qmnew file mode 100644index 0000000..395a8dfBinary files /dev/null and b/src/desktop/translations/app_ar.qm differdiff --git a/src/desktop/translations/app_de.qm b/src/desktop/translations/app_de.qmnew file mode 100644index 0000000..ad6f5d6Binary files /dev/null and b/src/desktop/translations/app_de.qm differdiff --git a/src/desktop/translations/app_es.qm b/src/desktop/translations/app_es.qmnew file mode 100644index 0000000..d7a7814Binary files /dev/null and b/src/desktop/translations/app_es.qm differdiff --git a/src/desktop/translations/app_fr.qm b/src/desktop/translations/app_fr.qmnew file mode 100644index 0000000..5c77efcBinary files /dev/null and b/src/desktop/translations/app_fr.qm differdiff --git a/src/desktop/translations/app_hi.qm b/src/desktop/translations/app_hi.qmnew file mode 100644index 0000000..40158b1Binary files /dev/null and b/src/desktop/translations/app_hi.qm differdiff --git a/src/desktop/translations/app_ja.qm b/src/desktop/translations/app_ja.qmnew file mode 100644index 0000000..061ae0bBinary files /dev/null and b/src/desktop/translations/app_ja.qm differdiff --git a/src/desktop/translations/app_ko.qm b/src/desktop/translations/app_ko.qmnew file mode 100644index 0000000..abcd647Binary files /dev/null and b/src/desktop/translations/app_ko.qm differdiff --git a/src/desktop/translations/app_pl.qm b/src/desktop/translations/app_pl.qmnew file mode 100644index 0000000..ddacc59Binary files /dev/null and b/src/desktop/translations/app_pl.qm differdiff --git a/src/desktop/translations/app_uk.qm b/src/desktop/translations/app_uk.qmnew file mode 100644index 0000000..96ff24cBinary files /dev/null and b/src/desktop/translations/app_uk.qm differdiff --git a/src/desktop/translations/app_zh_CN.qm b/src/desktop/translations/app_zh_CN.qmnew file mode 100644index 0000000..e13f90fBinary files /dev/null and b/src/desktop/translations/app_zh_CN.qm differdiff --git a/src/desktop/translations/app_zh_TW.qm b/src/desktop/translations/app_zh_TW.qmnew file mode 100644index 0000000..8d9c0b7Binary files /dev/null and b/src/desktop/translations/app_zh_TW.qm differdiff --git a/src/desktop/win_frameless.py b/src/desktop/win_frameless.pyindex 871b5b6..c946f11 100644--- a/src/desktop/win_frameless.py+++ b/src/desktop/win_frameless.py@@ -29,7 +29,7 @@ import timefrom ctypes import wintypesfrom pathlib import Path-from PySide6.QtCore import QAbstractNativeEventFilter, QCoreApplication+from PySide6.QtCore import QAbstractNativeEventFilter, QCoreApplication, Qtfrom ..core.paths import LOGS@@ -44,7 +44,7 @@ WM_NCLBUTTONDOWN = 0x00A1# so the QML unsaved-operation confirm dialog keeps working.SC_MINIMIZE = 0xF020SC_MAXIMIZE = 0xF030-SC_RESTORE = 0xF061+SC_RESTORE = 0xF060SW_MINIMIZE = 6SW_MAXIMIZE = 3@@ -330,27 +330,40 @@ class WinFramelessFilter(QAbstractNativeEventFilter):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+ try:+ state = self._window.windowState()+ except Exception:+ state = Qt.WindowNoState+ fullscreen = bool(state & Qt.WindowFullScreen)+ maximized = bool(state & Qt.WindowMaximized)+ try:+ maximized = maximized or bool(_user32().IsZoomed(self._hwnd))+ except Exception:+ pass++ # Resize only restored windows. The top of a maximized header must+ # remain a caption so dragging it can restore and move the window.+ if not maximized and not fullscreen:+ 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.@@ -363,7 +376,7 @@ class WinFramelessFilter(QAbstractNativeEventFilter):# 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:+ if not fullscreen and (py - cy) < HEADER_HEIGHT_DIP * dpr:return HTCAPTIONreturn HTCLIENTdiff --git a/src/desktop/window_focus.py b/src/desktop/window_focus.pynew file mode 100644index 0000000..00c3e53--- /dev/null+++ b/src/desktop/window_focus.py@@ -0,0 +1,43 @@+"""Dismiss a control's focus when the user clicks elsewhere in the window."""+from __future__ import annotations++from PySide6.QtCore import QEvent, QObject, Qt+from PySide6.QtQuick import QQuickWindow+++class ClickFocusFilter(QObject):+ """Observe clicks without consuming them or covering interactive content."""++ def __init__(self, window: QQuickWindow):+ super().__init__(window)+ window.installEventFilter(self)++ def eventFilter(self, window, event):+ if event.type() != QEvent.Type.MouseButtonPress or event.button() != Qt.MouseButton.LeftButton:+ return False+ focused = window.activeFocusItem()+ if focused is None or focused == window.contentItem():+ return False++ # A native ComboBox keeps keyboard focus while its popup is open.+ # Clearing it on a row press closes the popup before Qt can select+ # the row. Let Qt handle selection and clicks outside that popup.+ ancestor = focused+ while ancestor is not None:+ if ancestor.inherits("QQuickComboBox") and ancestor.property("down"):+ return False+ ancestor = ancestor.parentItem()++ boundary = focused+ # Our text editors live inside padded input boxes. Clicking that+ # padding or the field's clear button should keep the editor focused.+ if (focused.inherits("QQuickTextInput") or focused.inherits("QQuickTextEdit")):+ parent = focused.parentItem()+ if parent is not None and not focused.inherits("QQuickTextField"):+ boundary = parent+ local = boundary.mapFromScene(event.position())+ if not boundary.contains(local):+ # Qt commits text edits on focus loss before the clicked action+ # runs. The receiving control can then take focus normally.+ focused.setFocus(False, Qt.FocusReason.MouseFocusReason)+ return Falsediff --git a/src/desktop/window_geometry.py b/src/desktop/window_geometry.pynew file mode 100644index 0000000..06a7dc1--- /dev/null+++ b/src/desktop/window_geometry.py@@ -0,0 +1,49 @@+"""Restore the initial window rectangle once, then leave geometry to Qt/Windows."""+from __future__ import annotations++from PySide6.QtCore import QRect, QSize+from PySide6.QtGui import QGuiApplication, QScreen, QWindow+++def fit_restore_geometry(saved: QRect, minimum: QSize, screens: list[QScreen],+ preferred: QScreen, *, has_position: bool) -> tuple[QScreen, QRect]:+ """Use the saved monitor when present; recover safely after display changes.++ All rectangles are Qt device-independent coordinates. Screen origins may+ be negative, and mixed-DPI Windows screens need not touch in this space.+ """+ screen = preferred+ overlap = 0+ if has_position:+ for candidate in screens:+ intersection = saved.intersected(candidate.geometry())+ area = intersection.width() * intersection.height() if not intersection.isEmpty() else 0+ if area > overlap:+ screen, overlap = candidate, area+ work = screen.availableGeometry()+ width = max(minimum.width(), min(saved.width(), work.width()))+ height = max(minimum.height(), min(saved.height(), work.height()))+ # When a monitor has disappeared, center on a connected monitor instead+ # of leaving the window in an empty part of the virtual desktop.+ if has_position and overlap:+ x = saved.x()+ y = saved.y()+ else:+ x = work.x() + (work.width() - width) // 2+ y = work.y() + (work.height() - height) // 2+ x = max(work.x(), min(x, work.x() + max(0, work.width() - width)))+ y = max(work.y(), min(y, work.y() + max(0, work.height() - height)))+ return screen, QRect(x, y, width, height)+++def restore_window_geometry(window: QWindow, saved: QRect, *, has_position: bool) -> None:+ screens = QGuiApplication.screens()+ preferred = window.screen() or QGuiApplication.primaryScreen()+ if not screens or preferred is None:+ return+ screen, geometry = fit_restore_geometry(saved, window.minimumSize(), screens,+ preferred, has_position=has_position)+ # Select the monitor before setting its logical coordinates, so Qt uses+ # that monitor's scale factor when creating the native window.+ window.setScreen(screen)+ window.setGeometry(geometry)diff --git a/src/desktop/workers.py b/src/desktop/workers.pyindex f391ad0..b3b49c0 100644--- a/src/desktop/workers.py+++ b/src/desktop/workers.py@@ -14,6 +14,7 @@ class WorkerSignals(QObject):started = Signal()progress = Signal(float, str)itemUpdated = Signal(int, str, float, str, str, float)+ metadataReady = Signal(str, object)finished = Signal(object)failed = Signal(str)cancelled = Signal()diff --git a/src/desktop/workflow.py b/src/desktop/workflow.pyindex 8d1681d..a1be2cd 100644--- a/src/desktop/workflow.py+++ b/src/desktop/workflow.py@@ -1,883 +1,902 @@-"""Ordered, file-backed Neural Rendering workflow shared by preview and export."""--from __future__ import annotations-+"""Ordered, file-backed Neural Rendering workflow shared by preview and export."""++from __future__ import annotations+import subprocess-import shutil-import tempfile-import time-from dataclasses import dataclass, replace-from pathlib import Path--import numpy as np--from ..core import app_log, ffmpeg-from ..core.batch_progress import BatchProgress+import os+import shutil+import tempfile+import time+from dataclasses import dataclass, replace+from pathlib import Path++import numpy as np++from ..core import app_log, ffmpeg+from ..core.batch_progress import BatchProgressfrom ..core.cache_cleanup import prune_preview_cache-from ..core.disk_paths import OutputFile, prepare_output_dir-from ..core.dlss_modes import dlss_output_size-from ..core.ffmpeg.audio import plan_audio_streams+from ..core.cache_video import cache_ffmpeg_args, cache_video_format+from ..core.disk_paths import OutputFile, prepare_output_dir+from ..core.dlss_modes import dlss_output_size+from ..core.ffmpeg.audio import plan_audio_streamsfrom ..core.ffmpeg.encoder import _codec_command-from ..core.gpu_detection import detect_gpus-from ..core.jobs import Cancelled, JobController-from ..core.naming import output_filename, unique_output_path-from ..core.paths import (FFMPEG, JOBS, OUTPUTS, PREVIEW_CACHE,- DLSSSR_BRIDGE, DLSSSR_RUNTIME, DLSSNR_BRIDGE,- DLSSNR_CALLER_SHIM, DLSSG_DIR, RUNTIME,- NEURAL_RUNTIME)-from ..core.nr_composition import mask_selection-from ..core.runtime import resolve_output_size-from ..frame_interpolation.models import FrameInterpolationOptions, resolve_target_rate-from ..frame_interpolation.processor import interpolate_video-from ..neural_rendering.image.batch import convert_images-from ..neural_rendering.image.decoder import _open_pillow_source, decode_image-from ..neural_rendering.image.encoder import _encode_image-from ..neural_rendering.image.models import IMAGE_EXTENSIONS, ImageConversionOptions-from ..neural_rendering.video.models import ConversionOptions-from ..neural_rendering.video.processor import convert_video-from ..settings.models import (UISettings, IMAGE_SCALING_FILTERS, VIDEO_SCALING_FILTERS,- IMAGE_16BIT_FORMATS,- validate_stage_layout)-from ..upscale.image.models import options_from_settings as image_upscale_options, output_size as image_upscale_size-from ..upscale.image.processor import upscale_image-from ..upscale.video.models import options_from_settings as video_upscale_options, output_size as video_upscale_size-from ..upscale.video.processor import upscale_video-from .coloring import (apply_cube_lut, compose_cube_lut, has_lut_adjustments,- identity_cube_lut, load_cube_lut, match_image_colors, save_cube_lut)-from .cas_sharpening import sharpen_image, sharpen_video-from .denoising import denoise_image, denoise_video-from .preview_cache import PreviewStageCache, cache_key, file_identity, optional_file_identity---LOSSLESS_VIDEO = "FFV1 Lossless RGB 10-bit"-STAGE_LABELS = {- "denoising": "Denoising",- "neural_model": "DLSS Neural Rendering",- "scale_method": "Scaling",- "dlss_super_resolution": "DLSS Super Resolution",+from ..core.ffmpeg.preview import decode_preview_frame, extract_preview_subclip+from ..core.gpu_detection import detect_gpus+from ..core.jobs import Cancelled, JobController+from ..core.naming import output_filename, unique_output_path+from ..core.paths import (FFMPEG, JOBS, OUTPUTS, PREVIEW_CACHE,+ DLSSSR_BRIDGE, DLSSSR_RUNTIME, DLSSNR_BRIDGE,+ DLSSNR_CALLER_SHIM, DLSSG_DIR, RUNTIME,+ NEURAL_RUNTIME)+from ..core.nr_composition import mask_selection+from ..core.runtime import resolve_output_size+from ..frame_interpolation.models import FrameInterpolationOptions, resolve_target_rate+from ..frame_interpolation.processor import interpolate_video+from ..neural_rendering.image.batch import convert_images+from ..neural_rendering.image.decoder import _open_pillow_source, decode_image+from ..neural_rendering.image.encoder import _encode_image+from ..neural_rendering.image.models import IMAGE_EXTENSIONS, ImageConversionOptions+from ..neural_rendering.video.models import ConversionOptions+from ..neural_rendering.video.processor import convert_video+from ..settings.models import (UISettings, IMAGE_SCALING_FILTERS, VIDEO_SCALING_FILTERS,+ IMAGE_16BIT_FORMATS,+ validate_stage_layout)+from ..upscale.image.models import options_from_settings as image_upscale_options, output_size as image_upscale_size+from ..upscale.image.processor import upscale_image+from ..upscale.video.models import options_from_settings as video_upscale_options, output_size as video_upscale_size+from ..upscale.video.processor import upscale_video+from .coloring import (apply_cube_lut, compose_cube_lut, has_lut_adjustments,+ identity_cube_lut, load_cube_lut, match_image_colors, save_cube_lut)+from .cas_sharpening import sharpen_image, sharpen_video+from .preview_cache import PreviewStageCache, cache_key, file_identity, optional_file_identity+++LOSSLESS_VIDEO = "FFV1 Lossless RGB 10-bit"+STAGE_LABELS = {+ "neural_model": "DLSS Neural Rendering",+ "scale_method": "Scaling",+ "dlss_super_resolution": "DLSS Super Resolution","super_resolution": "RTX Super Resolution",- "frame_generation": "DLSS Frame Generation",- "coloring": "Coloring",- "cas_sharpening": "Sharpening",-}---_NR_FIELDS = (- "nr_style", "nr_intensity", "nr_passes", "local_tone_strength",- "local_structure_strength", "skin_structure_strength", "nr_color_strength",- "tone_preservation", "face_skin_protection", "grain_preservation",- "mask_feather", "automatic_mask",-)-_LUT_FIELDS = (- "lut_resolution", "lut_mix", "lut_exposure", "lut_contrast",- "lut_highlights", "lut_shadows", "lut_whites", "lut_blacks",- "lut_midtones", "lut_temperature", "lut_tint", "lut_hue",- "lut_vibrance", "lut_saturation",-)-_IMAGE_VSR_FIELDS = (- "upscale_image_vsr_quality", "upscale_image_size_mode",- "upscale_image_scale_factor", "upscale_image_width",- "upscale_image_height", "upscale_image_aspect_lock",-)+ "rtx_video_hdr": "RTX Video HDR",+ "frame_generation": "DLSS Frame Generation",+ "coloring": "Coloring",+ "cas_sharpening": "Sharpening",+}+++_NR_FIELDS = (+ "nr_style", "nr_intensity", "nr_passes", "local_tone_strength",+ "local_structure_strength", "skin_structure_strength", "nr_color_strength",+ "tone_preservation", "face_skin_protection", "grain_preservation",+ "mask_feather", "automatic_mask",+)+_LUT_FIELDS = (+ "lut_resolution", "lut_mix", "lut_exposure", "lut_contrast",+ "lut_highlights", "lut_shadows", "lut_whites", "lut_blacks",+ "lut_midtones", "lut_temperature", "lut_tint", "lut_hue",+ "lut_vibrance", "lut_saturation",+)+_IMAGE_VSR_FIELDS = (+ "upscale_image_vsr_quality", "upscale_image_size_mode",+ "upscale_image_scale_factor", "upscale_image_width",+ "upscale_image_height", "upscale_image_aspect_lock",+)_VIDEO_VSR_FIELDS = (- "upscale_vsr_enabled", "upscale_vsr_quality", "upscale_size_mode",+ "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_aspect_lock",)---def _preview_runtime_identity() -> list[dict | None]:- # A replaced processing engine must never inherit intermediates produced- # by the previous engine, including when the app is updated in place.- source_root = Path(__file__).resolve().parents[1]- return [optional_file_identity(path) for path in- (Path(__file__), Path(__file__).with_name("coloring.py"),- Path(__file__).with_name("denoising.py"),- Path(__file__).with_name("cas_sharpening.py"),- Path(__file__).with_name("nis_sharpening.py"),- source_root / "core" / "dlss_bridge.py",+_VIDEO_HDR_FIELDS = (+ "upscale_hdr_contrast",+ "upscale_hdr_saturation", "upscale_hdr_middle_gray",+ "upscale_hdr_peak_luminance", "upscale_hdr_precision",+)+++def _preview_runtime_identity() -> list[dict | None]:+ # A replaced processing engine must never inherit intermediates produced+ # by the previous engine, including when the app is updated in place.+ source_root = Path(__file__).resolve().parents[1]+ return [optional_file_identity(path) for path in+ (Path(__file__), Path(__file__).with_name("coloring.py"),+ Path(__file__).with_name("cas_sharpening.py"),+ source_root / "core" / "ffmpeg" / "vulkan.py",+ source_root / "core" / "ffmpeg" / "filters.py",+ source_root / "core" / "ffmpeg" / "sharpening.py",+ source_root / "core" / "dlss_bridge.py",source_root / "upscale" / "image" / "processor.py",source_root / "upscale" / "video" / "processor.py",- source_root / "neural_rendering" / "image" / "batch.py",- source_root / "neural_rendering" / "video" / "processor.py",- source_root / "frame_interpolation" / "processor.py",- FFMPEG, DLSSSR_BRIDGE, DLSSSR_RUNTIME, DLSSNR_BRIDGE,- DLSSNR_CALLER_SHIM, NEURAL_RUNTIME,- RUNTIME / "rtx_video" / "neuroframe_engine_upscaling.dll",- RUNTIME / "rtx_video" / "nvngx_vsr.dll",- RUNTIME / "rtx_video" / "nvngx_truehdr.dll",- DLSSG_DIR / "nvngx_dlssg.dll")]---def _stage_cache_settings(settings: UISettings, mode: str, stage: str, hdr: bool) -> dict:- """Only settings consumed by this card belong to its cache key."""- fields: tuple[str, ...]- extras: dict = {}- if stage == "denoising":- fields = ("denoise_strength", "denoise_deblock")- if mode == "Video":- fields += ("denoise_temporal",)- elif stage == "cas_sharpening":- fields = ("cas_sharpness", "sharpening_method")- elif stage == "neural_model":- fields = _NR_FIELDS + (("shimmer_suppression", "video_gpu_uuid") if mode == "Video" else ())- fields += ("ai_gpu_uuid",)- selected_mask = mask_selection(settings.nr_mask)- extras["mask"] = (None if selected_mask is None else- {**selected_mask.state(), "file": file_identity(selected_mask.path)})- extras["hdr_input"] = hdr- elif stage == "scale_method":- fields = ("upscaling_factor", "image_scaling_filter" if mode == "Image"- else "video_scaling_filter")- elif stage == "dlss_super_resolution":- fields = (("upscale_image_dlss_mode", "upscale_image_dlss_preset", "ai_gpu_uuid")- if mode == "Image" else- ("upscale_dlss_mode", "upscale_dlss_preset", "ai_gpu_uuid", "video_gpu_uuid"))+ source_root / "upscale" / "video" / "media.py",+ source_root / "upscale" / "video" / "host_pipeline.py",+ source_root / "neural_rendering" / "image" / "batch.py",+ source_root / "neural_rendering" / "video" / "processor.py",+ source_root / "frame_interpolation" / "processor.py",+ FFMPEG, DLSSSR_BRIDGE, DLSSSR_RUNTIME, DLSSNR_BRIDGE,+ DLSSNR_CALLER_SHIM, NEURAL_RUNTIME,+ RUNTIME / "rtx_video" / "neuroframe_engine_upscaling.dll",+ RUNTIME / "rtx_video" / "nvngx_vsr.dll",+ RUNTIME / "rtx_video" / "nvngx_truehdr.dll",+ DLSSG_DIR / "nvngx_dlssg.dll")]+++def _stage_cache_settings(settings: UISettings, mode: str, stage: str, hdr: bool) -> dict:+ """Only settings consumed by this card belong to its cache key."""+ fields: tuple[str, ...]+ extras: dict = {}+ if stage == "cas_sharpening":+ fields = ("cas_sharpness", "sharpening_method")+ elif stage == "neural_model":+ fields = _NR_FIELDS + (("shimmer_suppression", "video_gpu_uuid") if mode == "Video" else ())+ fields += ("ai_gpu_uuid",)+ selected_mask = mask_selection(settings.nr_mask)+ extras["mask"] = (None if selected_mask is None else+ {**selected_mask.state(), "file": file_identity(selected_mask.path)})+ extras["hdr_input"] = hdr+ elif stage == "scale_method":+ fields = ("upscaling_factor", "image_scaling_filter" if mode == "Image"+ else "video_scaling_filter")+ elif stage == "dlss_super_resolution":+ fields = (("upscale_image_dlss_mode", "upscale_image_dlss_preset", "ai_gpu_uuid")+ if mode == "Image" else+ ("upscale_dlss_mode", "upscale_dlss_preset", "ai_gpu_uuid", "video_gpu_uuid"))elif stage == "super_resolution":fields = (("ai_gpu_uuid",) + _IMAGE_VSR_FIELDS if mode == "Image" else("ai_gpu_uuid", "video_gpu_uuid") + _VIDEO_VSR_FIELDS)- elif stage == "frame_generation":- fields = ("frame_interpolation_target_fps", "frame_interpolation_engine",- "ai_gpu_uuid", "video_gpu_uuid")- extras["hdr_input"] = hdr- elif stage == "coloring":- fields = _LUT_FIELDS if mode == "Video" or settings.coloring_mode == "LUT" else ()- if mode == "Image":- fields += ("coloring_mode",)- if settings.coloring_mode == "Color Match":- fields += ("color_match_source",)- if settings.color_match_source == "Selected Image":- extras["reference"] = file_identity(settings.color_match_reference)- else:- extras["lut"] = (file_identity(settings.lut_path) if settings.lut_path else None)- else:- extras["lut"] = (file_identity(settings.lut_path) if settings.lut_path else None)- else:- raise ValueError(f"Unknown processing card: {stage}")- return {**{name: getattr(settings, name) for name in fields}, **extras}---def _video_scaling_filter(width: int, height: int, method: str) -> tuple[list[str], str]:- """Return FFmpeg device arguments and the exact requested scaler."""- if method == "Spline36":- return [], f"format=gbrp10le,zscale=w={width}:h={height}:filter=spline36:matrixin=gbr:matrix=gbr"- if method == "EWA Lanczos":- return ["-init_hw_device", "vulkan=vk:0", "-filter_hw_device", "vk"], (- "format=gbrp10le,hwupload,"- f"libplacebo=w={width}:h={height}:upscaler=ewa_lanczos:downscaler=ewa_lanczos,"- "hwdownload,format=gbrp10le"- )- flags = {"Lanczos": "lanczos", "Bicubic": "bicubic", "Area": "area", "Bilinear": "bilinear"}- if method not in flags:- raise ValueError(f"Unknown video scaling filter: {method!r}.")- return [], f"scale={width}:{height}:flags={flags[method]}"---@dataclass(frozen=True)-class PipelineEstimate:- width: int- height: int- fps: float- hdr: bool---@dataclass(frozen=True)-class PipelineSuccess:- input_path: str- output_path: str---@dataclass(frozen=True)-class PipelineFailure:- input_path: str- error: str- cancelled: bool = False---@dataclass(frozen=True)-class PipelineBatchResult:- successes: list[PipelineSuccess]- failures: list[PipelineFailure]- cancelled: bool--+ elif stage == "rtx_video_hdr":+ fields = ("ai_gpu_uuid", "video_gpu_uuid") + _VIDEO_HDR_FIELDS+ elif stage == "frame_generation":+ fields = ("frame_interpolation_target_fps", "frame_interpolation_engine",+ "ai_gpu_uuid", "video_gpu_uuid")+ extras["hdr_input"] = hdr+ elif stage == "coloring":+ fields = _LUT_FIELDS if mode == "Video" or settings.coloring_mode == "LUT" else ()+ if mode == "Image":+ fields += ("coloring_mode",)+ if settings.coloring_mode == "Color Match":+ fields += ("color_match_source",)+ if settings.color_match_source == "Selected Image":+ extras["reference"] = file_identity(settings.color_match_reference)+ else:+ extras["lut"] = (file_identity(settings.lut_path) if settings.lut_path else None)+ else:+ extras["lut"] = (file_identity(settings.lut_path) if settings.lut_path else None)+ else:+ raise ValueError(f"Unknown processing card: {stage}")+ return {"ffmpeg_device": settings.ffmpeg_device, **{name: getattr(settings, name) for name in fields}, **extras}+++def _video_scaling_filter(width: int, height: int, method: str) -> str:+ from ..core.ffmpeg.filters import scaling_filter+ return "ve_gpu," + scaling_filter(width, height, method)+++@dataclass(frozen=True)+class PipelineEstimate:+ width: int+ height: int+ fps: float+ hdr: bool+++@dataclass(frozen=True)+class PipelineSuccess:+ input_path: str+ output_path: str+++@dataclass(frozen=True)+class PipelineFailure:+ input_path: str+ error: str+ cancelled: bool = False+++@dataclass(frozen=True)+class PipelineBatchResult:+ successes: list[PipelineSuccess]+ failures: list[PipelineFailure]+ cancelled: bool++def enabled_stages(settings: UISettings, mode: str) -> tuple[str, ...]:- order = settings.image_stage_order if mode == "Image" else settings.video_stage_order- enabled = settings.image_enabled_stages if mode == "Image" else settings.video_enabled_stages- validate_stage_layout(order, enabled, video=mode == "Video")+ order = settings.image_stage_order if mode == "Image" else settings.video_stage_order+ enabled = settings.image_enabled_stages if mode == "Image" else settings.video_enabled_stages+ validate_stage_layout(order, enabled, video=mode == "Video")return tuple(stage for stage in order if stage in enabled)-def estimate_pipeline(width: int, height: int, fps: float, hdr: bool,- settings: UISettings, mode: str) -> PipelineEstimate:- """Preflight every enabled stage in its actual execution order."""- if width < 1 or height < 1:- raise ValueError("Input dimensions are unavailable.")- if mode == "Video" and fps <= 0:- raise ValueError("Input frame rate is unavailable; video export needs a known FPS.")+def preview_settings_key(settings: UISettings, mode: str, *, hdr: bool = False) -> str:+ """Identify the active pipeline, ignoring controls in disabled cards."""+ stages = []for stage in enabled_stages(settings, mode):- if stage == "denoising":- pass # Pixel size, frame rate and HDR flags are preserved.- elif stage == "cas_sharpening":- if mode == "Video" and hdr and settings.cas_sharpness:- raise ValueError("Sharpening requires SDR video at this position. Move it before HDR conversion.")- elif stage == "neural_model":- if min(width, height) < 64:- raise ValueError("DLSS Neural Rendering requires at least 64×64 input.")- resolve_output_size(width, height, 1.0)- elif stage == "scale_method":- selected_filter = settings.image_scaling_filter if mode == "Image" else settings.video_scaling_filter- choices = IMAGE_SCALING_FILTERS if mode == "Image" else VIDEO_SCALING_FILTERS- if selected_filter not in choices:- raise ValueError(f"Unknown {mode.lower()} scaling filter: {selected_filter!r}.")- if mode == "Video" and hdr:- raise ValueError("Scaling cannot process HDR video at this position. Move it before HDR conversion.")- width, height = resolve_output_size(width, height, settings.upscaling_factor)- elif stage == "dlss_super_resolution":- if mode == "Video" and hdr:- raise ValueError("DLSS Super Resolution cannot process HDR video at this position. Move it before HDR conversion.")- dlss_mode = settings.upscale_image_dlss_mode if mode == "Image" else settings.upscale_dlss_mode- width, height = dlss_output_size(width, height, dlss_mode, even=mode == "Video")- elif stage == "super_resolution":- if mode == "Image":- options = replace(image_upscale_options(settings), engine="RTX Video Super Resolution")- width, height = image_upscale_size(width, height, options)- else:- if hdr:- raise ValueError("RTX Super Resolution cannot process HDR video at this position. Move it before HDR conversion.")- opts = replace(video_upscale_options(settings), engine="RTX Video Super Resolution",- codec=LOSSLESS_VIDEO,- container="MKV", quality="Auto (Default)")+ stages.append((stage, _stage_cache_settings(settings, mode, stage, hdr)))+ if stage == "rtx_video_hdr":+ hdr = True+ return cache_key({"mode": mode, "stages": stages})+++def estimate_pipeline(width: int, height: int, fps: float, hdr: bool,+ settings: UISettings, mode: str) -> PipelineEstimate:+ """Preflight every enabled stage in its actual execution order."""+ if width < 1 or height < 1:+ raise ValueError("Input dimensions are unavailable.")+ if mode == "Video" and fps <= 0:+ raise ValueError("Input frame rate is unavailable; video export needs a known FPS.")+ for stage in enabled_stages(settings, mode):+ if stage == "cas_sharpening":+ if mode == "Video" and hdr and settings.cas_sharpness:+ raise ValueError("Sharpening requires SDR video at this position. Move it before HDR conversion.")+ elif stage == "neural_model":+ if min(width, height) < 64:+ raise ValueError("DLSS Neural Rendering requires at least 64×64 input.")+ resolve_output_size(width, height, 1.0)+ elif stage == "scale_method":+ selected_filter = settings.image_scaling_filter if mode == "Image" else settings.video_scaling_filter+ choices = IMAGE_SCALING_FILTERS if mode == "Image" else VIDEO_SCALING_FILTERS+ if selected_filter not in choices:+ raise ValueError(f"Unknown {mode.lower()} scaling filter: {selected_filter!r}.")+ if mode == "Video" and hdr:+ raise ValueError("Scaling cannot process HDR video at this position. Move it before HDR conversion.")+ width, height = resolve_output_size(width, height, settings.upscaling_factor)+ elif stage == "dlss_super_resolution":+ if mode == "Video" and hdr:+ raise ValueError("DLSS Super Resolution cannot process HDR video at this position. Move it before HDR conversion.")+ dlss_mode = settings.upscale_image_dlss_mode if mode == "Image" else settings.upscale_dlss_mode+ width, height = dlss_output_size(width, height, dlss_mode, even=mode == "Video")+ elif stage == "super_resolution":+ if mode == "Image":+ options = replace(image_upscale_options(settings), engine="RTX Video Super Resolution")+ width, height = image_upscale_size(width, height, options)+ else:+ if hdr:+ raise ValueError("RTX Super Resolution cannot process HDR video at this position. Move it before HDR conversion.")+ opts = _video_upscale_stage_options(settings, stage)opts.validate(for_render=True)width, height, _ = video_upscale_size(width, height, opts)- hdr = opts.hdr_enabled- elif stage == "frame_generation":+ elif stage == "rtx_video_hdr":if mode != "Video":- raise ValueError("DLSS Frame Generation accepts video only.")- target_fps = float(resolve_target_rate(settings.frame_interpolation_target_fps))- if fps <= 0:- raise ValueError("Frame Generation requires a known input frame rate.")- if target_fps <= fps:- raise ValueError(- f"DLSS Frame Generation target {target_fps:g} FPS must exceed the "- f"{fps:g} FPS entering this card. Choose a higher target FPS."- )- fps = target_fps- elif stage == "coloring":- if mode == "Video" or settings.coloring_mode == "LUT":- if settings.lut_path and not Path(settings.lut_path).is_file():- raise ValueError("The selected .cube LUT is unavailable.")- elif settings.color_match_source == "Selected Image":- if not settings.color_match_reference:- raise ValueError("Choose a reference image in Coloring before rendering.")- if not Path(settings.color_match_reference).is_file():- raise ValueError("The selected Color Match reference image is unavailable.")- else:- raise ValueError(f"Unknown processing card: {stage}")- if mode == "Video":- if (width % 2 or height % 2) and settings.codec != LOSSLESS_VIDEO:- raise ValueError(- f"Video export requires even dimensions; this sequence ends at {width}×{height}. "- "Choose an even output size in Scaling, DLSS Super Resolution, or RTX Super Resolution."- )- if hdr and not settings.hdr_mode:- raise ValueError("HDR output requires 10-bit HDR Mode in Export Settings.")- if hdr and not ffmpeg.hdr_mode_supported(settings.codec):- raise ValueError("HDR output requires a 10-bit capable codec in Export Settings.")- ffmpeg.validate_codec_container(settings.codec, ffmpeg.container_for_codec(settings.codec))- return PipelineEstimate(width, height, fps, hdr)---def preflight_source(source: Path, settings: UISettings, mode: str) -> PipelineEstimate:- if not source.is_file():- raise FileNotFoundError(source)- if "coloring" in enabled_stages(settings, mode) and (mode == "Video" or settings.coloring_mode == "LUT"):- if settings.lut_path:- load_cube_lut(settings.lut_path)- if mode == "Image":- if ("coloring" in enabled_stages(settings, mode)- and settings.coloring_mode == "Color Match"- and settings.color_match_source == "Selected Image"):- if not settings.color_match_reference:- raise ValueError("Choose a reference image in Coloring before rendering.")- reference = Path(settings.color_match_reference)- if not reference.is_file():- raise ValueError(f"Color Match reference image is unavailable: {reference}")- try:- reference_image, _ = _open_pillow_source(reference)- reference_image.close()- except Exception as exc:- raise ValueError(f"Color Match reference image cannot be opened: {reference}") from exc- image, _ = _open_pillow_source(source)- try:- width, height = image.size- if image.getexif().get(274) in {5, 6, 7, 8}:- width, height = height, width- finally:- image.close()- return estimate_pipeline(width, height, 0.0, False, settings, mode)- native_fg = ("frame_generation" in enabled_stages(settings, mode)- and settings.frame_interpolation_engine == "Native DLSSG")- metadata = ffmpeg.probe_video(source, count_mode="metadata",- inspect_timestamps=native_fg)- result = estimate_pipeline(int(metadata["width"]), int(metadata["height"]),- float(metadata["fps"]), bool(metadata.get("hdr")), settings, mode)- if "(NVIDIA NVENC)" in settings.codec:- ffmpeg.resolve_video_gpu(detect_gpus(), settings.video_gpu_uuid,- settings.codec, result.width, result.height)- if native_fg:- from ..frame_interpolation.capabilities import probe_frame_interpolation_capabilities- from ..frame_interpolation.scheduler import choose_interpolation_plan-- caps = probe_frame_interpolation_capabilities(settings.ai_gpu_uuid)- if not caps.available:- raise ValueError("DLSS Frame Generation is unavailable. " + caps.detail)- choose_interpolation_plan(metadata["rate"],- resolve_target_rate(settings.frame_interpolation_target_fps),- settings.frame_interpolation_engine,- caps.native_multiplier, cfr=bool(metadata["cfr"]))- return result--+ raise ValueError("RTX Video HDR accepts video only.")+ if hdr:+ raise ValueError("RTX Video HDR requires SDR video at this position.")+ opts = _video_upscale_stage_options(settings, stage)+ opts.validate(for_render=True)+ width, height, _ = video_upscale_size(width, height, opts)+ hdr = True+ elif stage == "frame_generation":+ if mode != "Video":+ raise ValueError("DLSS Frame Generation accepts video only.")+ target_fps = float(resolve_target_rate(settings.frame_interpolation_target_fps))+ if fps <= 0:+ raise ValueError("Frame Generation requires a known input frame rate.")+ if target_fps <= fps:+ raise ValueError(+ f"DLSS Frame Generation target {target_fps:g} FPS must exceed the "+ f"{fps:g} FPS entering this card. Choose a higher target FPS."+ )+ fps = target_fps+ elif stage == "coloring":+ if mode == "Video" or settings.coloring_mode == "LUT":+ if settings.lut_path and not Path(settings.lut_path).is_file():+ raise ValueError("The selected .cube LUT is unavailable.")+ elif settings.color_match_source == "Selected Image":+ if not settings.color_match_reference:+ raise ValueError("Choose a reference image in Coloring before rendering.")+ if not Path(settings.color_match_reference).is_file():+ raise ValueError("The selected Color Match reference image is unavailable.")+ else:+ raise ValueError(f"Unknown processing card: {stage}")+ if mode == "Video":+ if (width % 2 or height % 2) and settings.codec != LOSSLESS_VIDEO:+ raise ValueError(+ f"Video export requires even dimensions; this sequence ends at {width}×{height}. "+ "Choose an even output size in Scaling, DLSS Super Resolution, or RTX Super Resolution."+ )+ if hdr and not settings.hdr_mode:+ raise ValueError("HDR output requires 10-bit HDR Mode in Export Settings.")+ if hdr and not ffmpeg.hdr_mode_supported(settings.codec):+ raise ValueError("HDR output requires a 10-bit capable codec in Export Settings.")+ ffmpeg.resolve_container(settings.codec, settings.container)+ return PipelineEstimate(width, height, fps, hdr)+++def preflight_source(source: Path, settings: UISettings, mode: str) -> PipelineEstimate:+ if not source.is_file():+ raise FileNotFoundError(source)+ if "coloring" in enabled_stages(settings, mode) and (mode == "Video" or settings.coloring_mode == "LUT"):+ if settings.lut_path:+ load_cube_lut(settings.lut_path)+ if mode == "Image":+ if ("coloring" in enabled_stages(settings, mode)+ and settings.coloring_mode == "Color Match"+ and settings.color_match_source == "Selected Image"):+ if not settings.color_match_reference:+ raise ValueError("Choose a reference image in Coloring before rendering.")+ reference = Path(settings.color_match_reference)+ if not reference.is_file():+ raise ValueError(f"Color Match reference image is unavailable: {reference}")+ try:+ reference_image, _ = _open_pillow_source(reference)+ reference_image.close()+ except Exception as exc:+ raise ValueError(f"Color Match reference image cannot be opened: {reference}") from exc+ image, _ = _open_pillow_source(source)+ try:+ width, height = image.size+ if image.getexif().get(274) in {5, 6, 7, 8}:+ width, height = height, width+ finally:+ image.close()+ return estimate_pipeline(width, height, 0.0, False, settings, mode)+ native_fg = ("frame_generation" in enabled_stages(settings, mode)+ and settings.frame_interpolation_engine == "Native DLSSG")+ metadata = ffmpeg.probe_video(source, count_mode="metadata",+ inspect_timestamps=native_fg)+ result = estimate_pipeline(int(metadata["width"]), int(metadata["height"]),+ float(metadata["fps"]), bool(metadata.get("hdr")), settings, mode)+ if "(NVIDIA NVENC)" in settings.codec:+ ffmpeg.resolve_video_gpu(detect_gpus(), settings.video_gpu_uuid,+ settings.codec, result.width, result.height)+ if native_fg:+ from ..frame_interpolation.capabilities import probe_frame_interpolation_capabilities+ from ..frame_interpolation.scheduler import choose_interpolation_plan++ caps = probe_frame_interpolation_capabilities(settings.ai_gpu_uuid)+ if not caps.available:+ raise ValueError("DLSS Frame Generation is unavailable. " + caps.detail)+ choose_interpolation_plan(metadata["rate"],+ resolve_target_rate(settings.frame_interpolation_target_fps),+ settings.frame_interpolation_engine,+ caps.native_multiplier, cfr=bool(metadata["cfr"]))+ return result++def preflight_capabilities(settings: UISettings, mode: str,- controller: JobController | None = None,- stages_override: tuple[str, ...] | None = None) -> None:- """Reject unavailable processing hardware before writing any stage output."""- stages = stages_override if stages_override is not None else enabled_stages(settings, mode)+ controller: JobController | None = None,+ stages_override: tuple[str, ...] | None = None) -> None:+ """Reject unavailable processing hardware before writing any stage output."""+ stages = stages_override if stages_override is not None else enabled_stages(settings, mode)if not stages:return- needs_ai_gpu = bool(set(stages) & {"neural_model", "dlss_super_resolution", "super_resolution", "frame_generation"})- if needs_ai_gpu:- from ..core.gpu_selection import detect_gpu-- detect_gpu(settings.ai_gpu_uuid)- if mode == "Video" and "scale_method" in stages and settings.video_scaling_filter == "EWA Lanczos":- device_args, filter_graph = _video_scaling_filter(64, 64, "EWA Lanczos")- try:- _run_command([str(FFMPEG), "-hide_banner", "-loglevel", "error",- *device_args, "-f", "lavfi", "-i", "testsrc2=size=64x64:rate=1:duration=1",- "-vf", filter_graph, "-frames:v", "1", "-f", "null", "-"],- controller or JobController(), "EWA Lanczos capability check")- except RuntimeError as exc:- raise ValueError("EWA Lanczos requires FFmpeg libplacebo and an available Vulkan device.") from exc- if "super_resolution" in stages:- vsr = mode == "Image" or settings.upscale_vsr_enabled- hdr = mode == "Video" and settings.upscale_hdr_enabled- if vsr or hdr:- from ..upscale.video.native import probe_capabilities-- caps = probe_capabilities(settings.ai_gpu_uuid, controller=controller)- if vsr and not caps.vsr.get("available"):- raise ValueError("RTX Super Resolution requires an available RTX Video Super Resolution runtime.")- if hdr and not caps.hdr.get("available"):- raise ValueError("RTX Video HDR requires an available RTX Video HDR runtime.")- if "frame_generation" in stages:- from ..frame_interpolation.capabilities import probe_frame_interpolation_capabilities-- caps = probe_frame_interpolation_capabilities(settings.ai_gpu_uuid)- if not caps.available:- raise ValueError("DLSS Frame Generation is unavailable. " + caps.detail)--+ from ..core.ffmpeg.vulkan import filter_device+ filter_device(settings.ffmpeg_device)+ needs_ai_gpu = bool(set(stages) & {"neural_model", "dlss_super_resolution", "super_resolution", "rtx_video_hdr", "frame_generation"})+ if needs_ai_gpu:+ from ..core.gpu_selection import detect_gpu++ detect_gpu(settings.ai_gpu_uuid)+ if set(stages) & {"super_resolution", "rtx_video_hdr"}:+ from ..upscale.video.native import probe_capabilities++ caps = probe_capabilities(settings.ai_gpu_uuid, controller=controller)+ if "super_resolution" in stages and not caps.vsr.get("available"):+ raise ValueError("RTX Super Resolution requires an available RTX Video Super Resolution runtime.")+ if "rtx_video_hdr" in stages and not caps.hdr.get("available"):+ raise ValueError("RTX Video HDR requires an available RTX Video HDR runtime.")+ if "frame_generation" in stages:+ from ..frame_interpolation.capabilities import probe_frame_interpolation_capabilities++ caps = probe_frame_interpolation_capabilities(settings.ai_gpu_uuid)+ if not caps.available:+ raise ValueError("DLSS Frame Generation is unavailable. " + caps.detail)++def _run_command(command: list[str], controller: JobController, label: str,- *, cwd: Path | None = None) -> None:- if controller.cancel.is_set():- raise Cancelled("Render stopped by user.")- process = subprocess.Popen(command, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE,- cwd=cwd,- creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))- controller.register(process)- try:- while True:- if controller.cancel.is_set():- raise Cancelled("Render stopped by user.")- try:- _, stderr = process.communicate(timeout=0.2)- break- except subprocess.TimeoutExpired:- continue- if process.returncode:- raise RuntimeError(f"{label} failed: {stderr.decode('utf-8', 'replace')[-2500:]}")- finally:- if process.poll() is None:- process.terminate()- try:- process.wait(timeout=5)- except subprocess.TimeoutExpired:- process.kill()- process.wait(timeout=5)- controller.unregister(process)- if process.stderr:- process.stderr.close()---def _neural_image_options(settings: UISettings) -> ImageConversionOptions:- return 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,- 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,- automatic_mask=settings.automatic_mask, upscaling_factor=1.0,- scale_method="Standard", output_format="TIFF", quality=100,- preserve_metadata=False,- )--+ *, cwd: Path | None = None, progress=None, metadata: dict | None = None) -> None:+ from ..core.ffmpeg.vulkan import run+ run(command, controller, label, cwd=cwd, progress=progress, metadata=metadata)+++def _neural_image_options(settings: UISettings) -> ImageConversionOptions:+ return 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,+ 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,+ automatic_mask=settings.automatic_mask, upscaling_factor=1.0,+ scale_method="Standard", output_format="TIFF", quality=100,+ preserve_metadata=False,+ )++def _neural_video_options(settings: UISettings, hdr: bool) -> ConversionOptions:+ cache_codec, cache_container, _ = cache_video_format(settings.cache_codec)return 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,- 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,- automatic_mask=settings.automatic_mask, upscaling_factor=1.0,- scale_method="Standard", codec=LOSSLESS_VIDEO, container="MKV",- quality="Auto (Default)", preserve_hdr=hdr,- )+ 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,+ 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,+ automatic_mask=settings.automatic_mask, upscaling_factor=1.0,+ scale_method="Standard", codec=cache_codec, container=cache_container,+ quality="Auto (Default)", preserve_hdr=hdr,+ )+++def _video_upscale_stage_options(settings: UISettings, stage: str):+ # Each card owns its operation. Legacy combined-card switches must not+ # enable HDR inside VSR or cause the standalone HDR card to resize frames.+ cache_codec, cache_container, _ = cache_video_format(settings.cache_codec)+ return replace(video_upscale_options(settings),+ engine="DLSS" if stage == "dlss_super_resolution" else "RTX Video Super Resolution",+ vsr_enabled=stage != "rtx_video_hdr", hdr_enabled=stage == "rtx_video_hdr",+ codec=cache_codec, container=cache_container, quality="Auto (Default)")def _image_stage(source: Path, stage: str, settings: UISettings,- directory: Path, controller: JobController, progress) -> Path:- if stage == "denoising":- return denoise_image(source, settings, directory, controller, progress, _run_command)- if stage == "cas_sharpening":- return sharpen_image(source, settings, directory, controller, progress)- if stage == "neural_model":- result = convert_images([source], _neural_image_options(settings), progress,- output_dir=directory, controller=controller,- generate_previews=False, create_zip=False)- if result.failures:- raise RuntimeError(result.failures[0].error)- return Path(result.successes[0].output_path)- if stage == "scale_method":- from ..core.runtime import resize_fit- decoded = decode_image(source)- height, width = decoded.rgba.shape[:2]- target_width, target_height = resolve_output_size(width, height, settings.upscaling_factor)- output = directory / "scaled.tiff"+ directory: Path, controller: JobController, progress) -> Path:+ if stage == "cas_sharpening":+ return sharpen_image(source, settings, directory, controller, progress)+ if stage == "neural_model":+ result = convert_images([source], _neural_image_options(settings), progress,+ output_dir=directory, controller=controller,+ generate_previews=False, create_zip=False)+ if result.failures:+ raise RuntimeError(result.failures[0].error)+ return Path(result.successes[0].output_path)+ if stage == "scale_method":+ from ..core.runtime import resize_fit+ decoded = decode_image(source)+ height, width = decoded.rgba.shape[:2]+ target_width, target_height = resolve_output_size(width, height, settings.upscaling_factor)+ output = directory / "scaled.tiff"_encode_image(output, resize_fit(decoded.rgba, target_width, target_height,- interpolation=settings.image_scaling_filter),- ImageConversionOptions(output_format="TIFF", preserve_metadata=False),- {}, generate_preview=False, controller=controller,- has_transparency=decoded.alpha is not None)- return output- opts = replace(image_upscale_options(settings),- engine="DLSS" if stage == "dlss_super_resolution" else "RTX Video Super Resolution",- output_format="TIFF", quality=100)- result = upscale_image(source, opts, progress, output_dir=directory,- controller=controller, generate_previews=False)- return Path(result.output_path)---def _coloring_image_stage(current: Path, input_image: Path, settings: UISettings,- directory: Path, controller: JobController, progress) -> Path:- rendered = decode_image(current)- if settings.coloring_mode == "LUT":- lut = load_cube_lut(settings.lut_path) if settings.lut_path else identity_cube_lut()- if has_lut_adjustments(settings):- lut = compose_cube_lut(lut, settings, settings.lut_resolution)- matched = apply_cube_lut(rendered.rgba, lut)- message = "Applying LUT"- else:- reference = (input_image if settings.color_match_source == "Input Image"- else Path(settings.color_match_reference))- if current.resolve() == reference.resolve():- return current- target = decode_image(reference)- matched = match_image_colors(rendered.rgba, target.rgba)- message = "Matching colors"- if controller.cancel.is_set():- raise Cancelled("Render stopped by user.")- progress(0.8, message)- output = directory / "color-matched.tiff"- _encode_image(output, matched,- ImageConversionOptions(output_format="TIFF", preserve_metadata=False),- {}, generate_preview=False, controller=controller,- has_transparency=rendered.alpha is not None)- progress(1.0, "Coloring complete")- return output---def _coloring_video_stage(source: Path, settings: UISettings, directory: Path,- controller: JobController, progress) -> Path:- # Work in the stage directory so FFmpeg can use a simple relative LUT- # filename, including when the user's .cube path contains spaces or colons.- staged_lut = directory / "reference.cube"- if settings.lut_path and not has_lut_adjustments(settings):- shutil.copyfile(settings.lut_path, staged_lut)- else:- save_cube_lut(staged_lut, settings.lut_path or None, settings, controller=controller)- load_cube_lut(staged_lut)- metadata = ffmpeg.probe_video(source, count_mode="metadata", controller=controller)- color_args: list[str] = []- for key, flag in (("color_primaries", "-color_primaries"),- ("color_transfer", "-color_trc")):- value = metadata.get(key)- if value and value != "unknown":- color_args.extend((flag, str(value)))- output = directory / "coloring.mkv"- progress(0.1, "Applying LUT to video")- _run_command([str(FFMPEG), "-hide_banner", "-loglevel", "error", "-y",- "-i", str(source), "-map", "0:v:0", "-map_metadata", "0", "-an",- "-vf", "format=gbrp10le,lut3d=file=reference.cube:interp=trilinear,format=gbrp10le",- "-c:v", "ffv1", "-level", "3", "-pix_fmt", "gbrp10le",- "-fps_mode", "passthrough", *color_args, "-color_range", "pc",- str(output)], controller, "Video LUT", cwd=directory)- progress(1.0, "LUT complete")- return output---def _video_stage(source: Path, stage: str, settings: UISettings, hdr: bool,- directory: Path, controller: JobController, progress) -> Path:- if stage == "denoising":- return denoise_video(source, settings, directory, controller, progress, _run_command)- if stage == "cas_sharpening":- return sharpen_video(source, settings, directory, controller, progress)- if stage == "neural_model":- result = convert_video(source, _neural_video_options(settings, hdr), progress,- output_dir=directory, controller=controller)- elif stage == "scale_method":- metadata = ffmpeg.probe_video(source, count_mode="metadata", controller=controller)- width, height = resolve_output_size(int(metadata["width"]), int(metadata["height"]),- settings.upscaling_factor)- output = directory / "scaled.mkv"- device_args, filter_graph = _video_scaling_filter(width, height, settings.video_scaling_filter)- _run_command([str(FFMPEG), "-hide_banner", "-loglevel", "error", "-y",- *device_args, "-i", str(source),- "-map", "0:v:0", "-map_metadata", "0", "-vf", filter_graph, "-c:v", "ffv1",- "-level", "3", "-pix_fmt", "gbrp10le", str(output)],- controller, f"{settings.video_scaling_filter} scaling")- return output- elif stage in {"dlss_super_resolution", "super_resolution"}:- opts = video_upscale_options(settings)- opts = replace(opts, engine="DLSS" if stage == "dlss_super_resolution"- else "RTX Video Super Resolution",- hdr_enabled=False if stage == "dlss_super_resolution" else opts.hdr_enabled)- opts = replace(opts, codec=LOSSLESS_VIDEO, container="MKV", quality="Auto (Default)")- result = upscale_video(source, opts, progress, output_dir=directory, controller=controller)+ interpolation=settings.image_scaling_filter, controller=controller),+ ImageConversionOptions(output_format="TIFF", preserve_metadata=False),+ {}, generate_preview=False, controller=controller,+ has_transparency=decoded.alpha is not None)+ return output+ if stage not in {"dlss_super_resolution", "super_resolution"}:+ raise ValueError(f"Unknown image processing card: {stage}")+ opts = replace(image_upscale_options(settings),+ engine="DLSS" if stage == "dlss_super_resolution" else "RTX Video Super Resolution",+ output_format="TIFF", quality=100)+ result = upscale_image(source, opts, progress, output_dir=directory,+ controller=controller, generate_previews=False)+ return Path(result.output_path)+++def _coloring_image_stage(current: Path, input_image: Path, settings: UISettings,+ directory: Path, controller: JobController, progress) -> Path:+ rendered = decode_image(current)+ if settings.coloring_mode == "LUT":+ lut = load_cube_lut(settings.lut_path) if settings.lut_path else identity_cube_lut()+ if has_lut_adjustments(settings):+ lut = compose_cube_lut(lut, settings, settings.lut_resolution)+ matched = apply_cube_lut(rendered.rgba, lut, controller=controller)+ message = "Applying LUT"+ else:+ reference = (input_image if settings.color_match_source == "Input Image"+ else Path(settings.color_match_reference))+ if current.resolve() == reference.resolve():+ return current+ target = decode_image(reference)+ matched = match_image_colors(rendered.rgba, target.rgba)+ message = "Matching colors"+ if controller.cancel.is_set():+ raise Cancelled("Render stopped by user.")+ progress(0.8, message)+ output = directory / "color-matched.tiff"+ _encode_image(output, matched,+ ImageConversionOptions(output_format="TIFF", preserve_metadata=False),+ {}, generate_preview=False, controller=controller,+ has_transparency=rendered.alpha is not None)+ progress(1.0, "Coloring complete")+ return output+++def _coloring_video_stage(source: Path, settings: UISettings, directory: Path,+ controller: JobController, progress) -> Path:+ # Work in the stage directory so FFmpeg can use a simple relative LUT+ # filename, including when the user's .cube path contains spaces or colons.+ staged_lut = directory / "reference.cube"+ if settings.lut_path and not has_lut_adjustments(settings):+ shutil.copyfile(settings.lut_path, staged_lut)+ else:+ save_cube_lut(staged_lut, settings.lut_path or None, settings, controller=controller)+ load_cube_lut(staged_lut)+ metadata = ffmpeg.probe_video(source, count_mode="metadata", controller=controller)+ output = directory / ("coloring" + cache_video_format(settings.cache_codec)[2])+ progress(0.0, "Applying LUT to video")+ _run_command([str(FFMPEG), "-hide_banner", "-loglevel", "error", "-y",+ "-i", str(source), "-map", "0:v:0", "-map_metadata", "0", "-an",+ "-vf", "ve_gpu,libplacebo=lut=reference.cube:lut_type=native:deband=0:dithering=-1:format=gbrp10le",+ *cache_ffmpeg_args(settings.cache_codec, metadata),+ "-fps_mode", "passthrough",+ str(output)], controller, "Applying LUT to video", cwd=directory,+ progress=progress, metadata=metadata)+ progress(1.0, "LUT complete")+ return output+++def _video_stage(source: Path, stage: str, settings: UISettings, hdr: bool,+ directory: Path, controller: JobController, progress) -> Path:+ if stage == "cas_sharpening":+ return sharpen_video(source, settings, directory, controller, progress)+ if stage == "neural_model":+ result = convert_video(source, _neural_video_options(settings, hdr), progress,+ output_dir=directory, controller=controller)+ elif stage == "scale_method":+ metadata = ffmpeg.probe_video(source, count_mode="metadata", controller=controller)+ width, height = resolve_output_size(int(metadata["width"]), int(metadata["height"]),+ settings.upscaling_factor)+ output = directory / ("scaled" + cache_video_format(settings.cache_codec)[2])+ filter_graph = _video_scaling_filter(width, height, settings.video_scaling_filter)+ _run_command([str(FFMPEG), "-hide_banner", "-loglevel", "error", "-y",+ "-i", str(source),+ "-map", "0:v:0", "-map_metadata", "0", "-vf", filter_graph,+ *cache_ffmpeg_args(settings.cache_codec, metadata), str(output)],+ controller, f"{settings.video_scaling_filter} scaling",+ progress=progress, metadata=metadata)+ return output+ elif stage in {"dlss_super_resolution", "super_resolution", "rtx_video_hdr"}:+ opts = _video_upscale_stage_options(settings, stage)+ result = upscale_video(source, opts, progress, output_dir=directory, controller=controller)elif stage == "frame_generation":+ cache_codec, cache_container, _ = cache_video_format(settings.cache_codec)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=LOSSLESS_VIDEO, container="MKV", quality="Auto (Default)",- hdr_mode=hdr,- )- result = interpolate_video(source, opts, progress, output_dir=directory,- controller=controller)- else:- raise ValueError(f"Unknown video processing card: {stage}")- return Path(result.output_path)---def _image_at_bit_depth(rgba: np.ndarray, settings: UISettings) -> np.ndarray:- """Convert the processed pixels to the requested delivery depth."""- depth = settings.image_bit_depth- if depth == 16:- if settings.image_format not in IMAGE_16BIT_FORMATS:- raise ValueError("16-bit image output is available for PNG and TIFF only.")- if rgba.dtype == np.uint8:- return rgba.astype(np.uint16) * 257- return rgba- if depth == 8:- if rgba.dtype == np.uint16:- return ((rgba.astype(np.uint32) + 128) // 257).astype(np.uint8)- return rgba- raise ValueError("Image bit depth must be 8 or 16 bits.")---def _export_image(current: Path, destination: Path,- settings: UISettings, controller: JobController) -> None:- rendered = decode_image(current)- pixels = _image_at_bit_depth(rendered.rgba, settings)- opts = ImageConversionOptions(output_format=settings.image_format,- quality=settings.image_quality,- preserve_metadata=False)+ 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=cache_codec, container=cache_container, quality="Auto (Default)",+ hdr_mode=hdr,+ )+ result = interpolate_video(source, opts, progress, output_dir=directory,+ controller=controller)+ else:+ raise ValueError(f"Unknown video processing card: {stage}")+ return Path(result.output_path)+++def _image_at_bit_depth(rgba: np.ndarray, settings: UISettings) -> np.ndarray:+ """Convert the processed pixels to the requested delivery depth."""+ depth = settings.image_bit_depth+ if depth == 16:+ if settings.image_format not in IMAGE_16BIT_FORMATS:+ raise ValueError("16-bit image output is available for PNG and TIFF only.")+ if rgba.dtype == np.uint8:+ return rgba.astype(np.uint16) * 257+ return rgba+ if depth == 8:+ if rgba.dtype == np.uint16:+ return ((rgba.astype(np.uint32) + 128) // 257).astype(np.uint8)+ return rgba+ raise ValueError("Image bit depth must be 8 or 16 bits.")+++def _export_image(current: Path, destination: Path,+ settings: UISettings, controller: JobController) -> None:+ rendered = decode_image(current)+ pixels = _image_at_bit_depth(rendered.rgba, settings)+ opts = ImageConversionOptions(output_format=settings.image_format,+ quality=settings.image_quality,+ preserve_metadata=False)+ output = OutputFile(destination)+ try:+ _encode_image(output.temporary, pixels, opts, {},+ generate_preview=False, controller=controller,+ has_transparency=rendered.alpha is not None)+ if controller.cancel.is_set():+ raise Cancelled("Render stopped by user.")+ output.publish()+ finally:+ output.cleanup()+++def _publish_video_preview(current: Path, destination: Path, controller: JobController) -> Path:+ """Keep the completed lossless clip available without another encode.++ A hard link is enough on the same volume. Cross-volume or optional-cache+ fallback copies remain cancellable and are published atomically.+ """+ destination = destination.with_suffix(current.suffix)+ destination.parent.mkdir(parents=True, exist_ok=True)output = OutputFile(destination)try:- _encode_image(output.temporary, pixels, opts, {},- generate_preview=False, controller=controller,- has_transparency=rendered.alpha is not None)if controller.cancel.is_set():- raise Cancelled("Render stopped by user.")+ raise Cancelled("Preview cancelled.")+ output.temporary.unlink()+ try:+ os.link(current, output.temporary)+ except OSError:+ with current.open("rb") as source, output.temporary.open("wb") as target:+ while data := source.read(1024 * 1024):+ if controller.cancel.is_set():+ raise Cancelled("Preview cancelled.")+ target.write(data)+ if controller.cancel.is_set():+ raise Cancelled("Preview cancelled.")output.publish()finally:output.cleanup()+ return destinationdef _export_video(source: Path, current: Path, destination: Path,settings: UISettings, controller: JobController,- *, preview: bool = False, pipeline_hdr: bool = False) -> None:- metadata = ffmpeg.probe_video(current, count_mode="metadata", controller=controller)- width, height = int(metadata["width"]), int(metadata["height"])- codec = "H.264" if preview else settings.codec- quality = "Best" if preview else settings.quality- container = "MP4" if preview else ffmpeg.container_for_codec(codec)- current_hdr = bool(metadata.get("hdr")) or pipeline_hdr- hdr = current_hdr and not preview- source_metadata = ffmpeg.probe_video(source, count_mode="metadata", controller=controller)- encode_metadata = dict(metadata)- # FFV1 RGB intermediates report matrix=gbr. Delivery codecs need the- # original YUV matrix, or BT.2020 for HDR created by Super Resolution.- if metadata.get("color_space") == "gbr" and codec != LOSSLESS_VIDEO:- encode_metadata["color_space"] = "bt2020nc" if hdr else (- source_metadata.get("color_space")- if source_metadata.get("color_space") not in {None, "", "unknown", "gbr"}- else "bt709"- )- encode_metadata["color_range"] = "tv"- if hdr:- encode_metadata["color_primaries"] = "bt2020"- encode_metadata["color_transfer"] = "smpte2084"- encode_metadata["color_space"] = "bt2020nc"- elif preview and current_hdr:- encode_metadata.update(color_space="bt709", color_primaries="bt709",- color_transfer="bt709", color_range="tv")- tone_map = None- if preview and current_hdr:- tone_map = (- "zscale=matrixin=gbr:primariesin=bt2020:transferin=smpte2084:rangein=full:"- "transfer=linear:npl=100,format=gbrpf32le,zscale=primaries=bt709,"- "tonemap=mobius:desat=2:peak=10,zscale=transfer=bt709:matrix=bt709:"- "range=limited,format=yuv420p"- )- gpu = ffmpeg.resolve_video_gpu(detect_gpus(), settings.video_gpu_uuid,- codec, width, height)- codec_args, _, _ = _codec_command(codec, quality, width, height,- float(metadata["fps"]),+ *, pipeline_hdr: bool = False, progress=None,+ video_filter: str | None = None, output_metadata: dict | None = None,+ working_directory: Path | None = None, verify_output: bool = False) -> None:+ metadata = output_metadata or ffmpeg.probe_video(current, count_mode="metadata", controller=controller)+ width, height = int(metadata["width"]), int(metadata["height"])+ codec = settings.codec+ quality = settings.quality+ container = ffmpeg.resolve_container(codec, settings.container)+ current_hdr = bool(metadata.get("hdr")) or pipeline_hdr+ hdr = current_hdr+ source_metadata = ffmpeg.probe_video(source, count_mode="metadata", controller=controller)+ encode_metadata = dict(metadata)+ # FFV1 RGB intermediates report matrix=gbr. Delivery codecs need the+ # original YUV matrix, or BT.2020 for HDR created by RTX Video HDR.+ if metadata.get("color_space") == "gbr" and codec != LOSSLESS_VIDEO:+ encode_metadata["color_space"] = "bt2020nc" if hdr else (+ source_metadata.get("color_space")+ if source_metadata.get("color_space") not in {None, "", "unknown", "gbr"}+ else "bt709"+ )+ encode_metadata["color_range"] = "tv"+ if hdr:+ encode_metadata["color_primaries"] = "bt2020"+ encode_metadata["color_transfer"] = "smpte2084"+ encode_metadata["color_space"] = "bt2020nc"+ gpu = ffmpeg.resolve_video_gpu((), settings.video_gpu_uuid,+ codec, width, height)+ codec_args, _, _ = _codec_command(codec, quality, width, height,+ float(metadata["fps"]),None if gpu is None else int(gpu["cuda_ordinal"]),hdr_mode=hdr, hdr_metadata=encode_metadata,- speed_profile="preview" if preview else "default")- audio = plan_audio_streams(source, container, controller)- output = OutputFile(destination)- try:+ speed_profile="default")+ audio = plan_audio_streams(source, container, controller)+ output = OutputFile(destination)+ try:command = [str(FFMPEG), "-hide_banner", "-loglevel", "error", "-y",- "-i", str(current), "-i", str(source),+ *(["-xerror"] if verify_output else []),+ "-i", str(current), "-i", str(source),"-map", "0:v:0", "-map", "1:a?", "-map_metadata", "1",- "-map_chapters", "1", *codec_args,- *(["-vf", tone_map, "-color_primaries", "bt709", "-color_trc", "bt709",- "-colorspace", "bt709", "-color_range", "tv"] if tone_map else []),- *audio.encoder_args(), "-fps_mode", "passthrough",- "-t", f"{max(float(metadata.get('duration') or 0), 1 / float(metadata['fps'])):.9f}",- str(output.temporary)]- _run_command(command, controller, "Video export")+ "-map_chapters", "1", *(["-vf", video_filter] if video_filter else []), *codec_args,+ *audio.encoder_args(), "-fps_mode", "passthrough",+ "-t", f"{max(float(metadata.get('duration') or 0), 1 / float(metadata['fps'])):.9f}",+ str(output.temporary)]+ _run_command(command, controller, "Video export", progress=progress, metadata=metadata,+ cwd=working_directory)if controller.cancel.is_set():raise Cancelled("Render stopped by user.")+ if verify_output:+ saved = ffmpeg.probe_video(output.temporary, count_mode="packets", controller=controller)+ if ((int(saved["width"]), int(saved["height"])) != (width, height)+ or int(saved["frames"]) < 1+ or (int(metadata.get("frames") or 0) > 0+ and int(saved["frames"]) != int(metadata["frames"]))):+ raise RuntimeError("Video export frame count or dimensions do not match the processing pipeline.")+ if hdr and (not saved.get("hdr") or int(saved.get("depth") or 0) < 10):+ raise RuntimeError("Video export lost HDR signaling or precision.")+ if controller.cancel.is_set():+ raise Cancelled("Render stopped by user.")output.publish()- finally:- output.cleanup()---def render_item(source: Path, settings: UISettings, mode: str, destination: Path,- controller: JobController, progress=None, *, preview: bool = False,- capabilities_checked: bool = False,- preview_cache: PreviewStageCache | None = None,+ finally:+ output.cleanup()+++def render_item(source: Path, settings: UISettings, mode: str, destination: Path,+ controller: JobController, progress=None, *, preview: bool = False,+ capabilities_checked: bool = False,+ preview_cache: PreviewStageCache | None = None,source_cache_key: str | None = None) -> str:- preflight_source(source, settings, mode)- if not capabilities_checked and preview_cache is None:- preflight_capabilities(settings, mode, controller)- stages = enabled_stages(settings, mode)- upstream_key = (source_cache_key or cache_key({"kind": "source", "mode": mode,- "source": file_identity(source)})) if preview_cache else ""- JOBS.mkdir(parents=True, exist_ok=True)+ controller.ffmpeg_device = settings.ffmpeg_device+ preflight_source(source, settings, mode)+ if not capabilities_checked and preview_cache is None:+ preflight_capabilities(settings, mode, controller)+ stages = enabled_stages(settings, mode)+ upstream_key = (source_cache_key or cache_key({"kind": "source", "mode": mode,+ "source": file_identity(source)})) if preview_cache else ""+ JOBS.mkdir(parents=True, exist_ok=True)with tempfile.TemporaryDirectory(prefix="visual-workflow-", dir=JOBS) as temp:+ if mode == "Video" and not preview and settings.cache_memory_mode == "rolling":+ from .rolling_workflow import render_rolling_video+ destination.parent.mkdir(parents=True, exist_ok=True)+ return render_rolling_video(source, settings, destination, controller,+ Path(temp), stages, progress)current = source- hdr = False- if mode == "Video":- hdr = bool(ffmpeg.probe_video(source, count_mode="metadata", controller=controller).get("hdr"))- for index, stage in enumerate(stages):- if controller.cancel.is_set():- raise Cancelled("Render stopped by user.")- stage_key = (cache_key({"kind": "stage", "mode": mode, "upstream": upstream_key,- "stage": stage,- "settings": _stage_cache_settings(settings, mode, stage, hdr)})- if preview_cache else "")- if preview_cache:- cached = preview_cache.lookup(stage_key, current)- if cached is not None:- current = cached- if progress:- progress((index + 1) / (len(stages) + 1),- f"{STAGE_LABELS[stage]}: using Smart cache")- upstream_key = stage_key- if stage == "super_resolution" and mode == "Video":- hdr = bool(settings.upscale_hdr_enabled)- continue- directory = Path(temp) / f"{index:02d}-{stage}"- directory.mkdir()- stage_input = current- if preview_cache and not capabilities_checked:- preflight_capabilities(settings, mode, controller, (stage,))+ # Smart previews remain lossless and share their existing FFV1 cache keys.+ stage_settings = replace(settings, cache_codec="FFV1") if preview else settings+ hdr = False+ if mode == "Video":+ hdr = bool(ffmpeg.probe_video(source, count_mode="metadata", controller=controller).get("hdr"))+ for index, stage in enumerate(stages):+ if controller.cancel.is_set():+ raise Cancelled("Render stopped by user.")+ stage_key = (cache_key({"kind": "stage", "mode": mode, "upstream": upstream_key,+ "stage": stage,+ "settings": _stage_cache_settings(settings, mode, stage, hdr)})+ if preview_cache else "")+ if preview_cache:+ cached = preview_cache.lookup(stage_key, current)+ if cached is not None:+ current = cached+ if progress:+ progress((index + 1) / (len(stages) + 1),+ f"Stage {index + 1} of {len(stages) + 1} · {STAGE_LABELS[stage]}: using Smart cache")+ upstream_key = stage_key+ if stage == "rtx_video_hdr":+ hdr = True+ continue+ directory = Path(temp) / f"{index:02d}-{stage}"+ directory.mkdir()+ stage_input = current+ if preview_cache and not capabilities_checked:+ preflight_capabilities(settings, mode, controller, (stage,))def report(value, message, i=index, name=stage):if progress:progress((i + max(0.0, min(1.0, float(value)))) / (len(stages) + 1),- f"{STAGE_LABELS[name]}: {message}")- if stage == "coloring":- current = (_coloring_image_stage(current, source, settings, directory, controller, report)- if mode == "Image" else- _coloring_video_stage(current, settings, directory, controller, report))- elif mode == "Image":- current = _image_stage(current, stage, settings, directory, controller, report)- else:- current = _video_stage(current, stage, settings, hdr, directory, controller, report)- if controller.cancel.is_set():- raise Cancelled("Render stopped by user.")- if preview_cache:- current = preview_cache.publish(stage_key, directory, current,- previous=stage_input)- upstream_key = stage_key- if stage == "super_resolution" and mode == "Video":- hdr = bool(settings.upscale_hdr_enabled)- if progress:- progress(len(stages) / (len(stages) + 1), "Exporting result")- destination.parent.mkdir(parents=True, exist_ok=True)- if mode == "Image":- _export_image(current, destination, settings, controller)+ f"Stage {i + 1} of {len(stages) + 1} · {STAGE_LABELS[name]}: {message}")+ report(0.0, "Preparing")+ if stage == "coloring":+ current = (_coloring_image_stage(current, source, settings, directory, controller, report)+ if mode == "Image" else+ _coloring_video_stage(current, stage_settings, directory, controller, report))+ elif mode == "Image":+ current = _image_stage(current, stage, settings, directory, controller, report)+ else:+ current = _video_stage(current, stage, stage_settings, hdr, directory, controller, report)+ if controller.cancel.is_set():+ raise Cancelled("Render stopped by user.")+ if preview_cache:+ current = preview_cache.publish(stage_key, directory, current,+ previous=stage_input)+ upstream_key = stage_key+ if stage == "rtx_video_hdr":+ hdr = True+ if progress:+ progress(len(stages) / (len(stages) + 1),+ "Preparing cached preview" if preview and mode == "Video" else+ f"Stage {len(stages) + 1} of {len(stages) + 1} · Exporting result")+ destination.parent.mkdir(parents=True, exist_ok=True)+ if mode == "Image":+ _export_image(current, destination, settings, controller)+ elif preview:+ destination = _publish_video_preview(current, destination, controller)else:+ def report_export(value, message):+ if progress:+ progress((len(stages) + max(0.0, min(.99, float(value)))) / (len(stages) + 1),+ f"Stage {len(stages) + 1} of {len(stages) + 1} · Exporting result: {message}")_export_video(source, current, destination, settings, controller,- preview=preview, pipeline_hdr=hdr)- if progress:- progress(1.0, "Export complete")- return str(destination)---def render_pipeline_batch(input_paths, settings: UISettings, mode: str,- progress=None, *, output_dir=None, controller=None,- on_item_update=None, same_as_input=False) -> PipelineBatchResult:- paths = [Path(path).resolve() for path in input_paths]- if not paths:- raise ValueError("Add a file before rendering.")- controller = controller or JobController()- for path in paths:- preflight_source(path, settings, mode)- preflight_capabilities(settings, mode, controller)- reporter = BatchProgress(paths, on_item_update, progress)- successes: list[PipelineSuccess] = []- failures: list[PipelineFailure] = []- reserved: set[Path] = set()- stamp = time.strftime("%Y%m%d-%H%M%S")- try:- for index, path in enumerate(paths):- if controller.cancel.is_set():- break- reporter.advance(index, 0.0, "Preparing pipeline")- folder = prepare_output_dir(path.parent if same_as_input else output_dir, default=OUTPUTS)- extension = (IMAGE_EXTENSIONS[settings.image_format] if mode == "Image" else- {"MP4": ".mp4", "MKV": ".mkv", "MOV": ".mov"}[ffmpeg.container_for_codec(settings.codec)])- rename_mode = settings.image_rename_mode if mode == "Image" else settings.video_rename_mode- suffix = settings.image_custom_suffix if mode == "Image" else settings.video_custom_suffix- output = unique_output_path(folder / output_filename(- path, extension, rename_mode, suffix, f"{path.stem}_Pipeline_{stamp}"), reserved)- reserved.add(output)- try:- rendered = render_item(path, settings, mode, output, controller,- lambda value, message, i=index: reporter.advance(i, value, message),- capabilities_checked=True)- except Exception as exc:- cancelled = isinstance(exc, Cancelled) or controller.cancel.is_set()- failures.append(PipelineFailure(str(path), str(exc), cancelled))- reporter.fail(index, exc, cancelled=cancelled)- if cancelled:- controller.stop()- break- else:- successes.append(PipelineSuccess(str(path), rendered))- reporter.complete(index, rendered)- if controller.cancel.is_set():- reporter.skip_from(0)- reporter.finish(cancelled=controller.cancel.is_set(), manifest_path=app_log.session_path())- return PipelineBatchResult(successes, failures, controller.cancel.is_set())- except BaseException as exc:- reporter.finish(cancelled=controller.cancel.is_set(), error=str(exc))- raise---def render_pipeline_preview(source: str, settings: UISettings, mode: str, *,- output_dir: Path, controller=None, progress=None,- start_seconds: float = 0.0,- clip_seconds: float | None = None,- cache_dir: Path = PREVIEW_CACHE) -> tuple[str, str]:+ pipeline_hdr=hdr, progress=report_export)+ if progress:+ progress(1.0, "Preview ready" if preview else "Export complete")+ return str(destination)+++def render_pipeline_batch(input_paths, settings: UISettings, mode: str,+ progress=None, *, output_dir=None, controller=None,+ on_item_update=None, same_as_input=False) -> PipelineBatchResult:+ paths = [Path(path).resolve() for path in input_paths]+ if not paths:+ raise ValueError("Add a file before rendering.")+ controller = controller or JobController()+ for path in paths:+ preflight_source(path, settings, mode)+ preflight_capabilities(settings, mode, controller)+ reporter = BatchProgress(paths, on_item_update, progress)+ successes: list[PipelineSuccess] = []+ failures: list[PipelineFailure] = []+ reserved: set[Path] = set()+ stamp = time.strftime("%Y%m%d-%H%M%S")+ try:+ for index, path in enumerate(paths):+ if controller.cancel.is_set():+ break+ reporter.advance(index, 0.0, "Preparing pipeline")+ folder = prepare_output_dir(path.parent if same_as_input else output_dir, default=OUTPUTS)+ extension = (IMAGE_EXTENSIONS[settings.image_format] if mode == "Image" else+ {"MP4": ".mp4", "MKV": ".mkv", "MOV": ".mov"}[+ ffmpeg.resolve_container(settings.codec, settings.container)])+ rename_mode = settings.image_rename_mode if mode == "Image" else settings.video_rename_mode+ suffix = settings.image_custom_suffix if mode == "Image" else settings.video_custom_suffix+ output = unique_output_path(folder / output_filename(+ path, extension, rename_mode, suffix, f"{path.stem}_Pipeline_{stamp}"), reserved)+ reserved.add(output)+ try:+ rendered = render_item(path, settings, mode, output, controller,+ lambda value, message, i=index: reporter.advance(i, value, message),+ capabilities_checked=True)+ except Exception as exc:+ cancelled = isinstance(exc, Cancelled) or controller.cancel.is_set()+ failures.append(PipelineFailure(str(path), str(exc), cancelled))+ reporter.fail(index, exc, cancelled=cancelled)+ if cancelled:+ controller.stop()+ break+ else:+ successes.append(PipelineSuccess(str(path), rendered))+ reporter.complete(index, rendered)+ if controller.cancel.is_set():+ reporter.skip_from(0)+ reporter.finish(cancelled=controller.cancel.is_set(), manifest_path=app_log.session_path())+ return PipelineBatchResult(successes, failures, controller.cancel.is_set())+ except BaseException as exc:+ reporter.finish(cancelled=controller.cancel.is_set(), error=str(exc))+ raise+++def render_pipeline_preview(source: str, settings: UISettings, mode: str, *,+ output_dir: Path, controller=None, progress=None,+ start_seconds: float = 0.0,+ clip_seconds: float | None = None,+ cache_dir: Path = PREVIEW_CACHE) -> tuple[str | np.ndarray, str]:controller = controller or JobController()source_path = Path(source).resolve()+ if controller.cancel.is_set():+ raise Cancelled("Preview cancelled.")+ if not source_path.is_file():+ raise FileNotFoundError(source_path)+ if not enabled_stages(settings, mode):+ # The native player already seeks/plays the unprocessed video. Do not+ # probe, convert to FFV1, or decode another copy just to show it again.+ media = decode_image(source_path).rgba if mode == "Image" else str(source_path)+ return media, "Source preview (all processing cards are off)."+ if mode == "Video":+ # Preview storage and playback are independent of delivery settings.+ settings = replace(settings, codec=LOSSLESS_VIDEO, container="MKV",+ quality="Auto (Default)", hdr_mode=True)preflight_source(source_path, settings, mode)- if mode == "Image" and not enabled_stages(settings, mode):- decoded = decode_image(source_path)- return decoded.rgba, "Source preview (all processing cards are off)."- stage_cache = PreviewStageCache(cache_dir)- root_key = cache_key({"kind": "source", "mode": mode,- "source": file_identity(source_path),- "runtime": _preview_runtime_identity()})- output_dir = prepare_output_dir(output_dir)- if mode == "Image":- output = unique_output_path(output_dir / f"pipeline-preview-{time.time_ns()}.png")- preview_settings = replace(settings, image_format="PNG", image_quality=100)- path = render_item(source_path, preview_settings, mode, output, controller, progress,- preview=True,- preview_cache=stage_cache, source_cache_key=root_key)- prune_preview_cache(root=stage_cache.root, protected_keys=stage_cache.used_keys,- min_idle_seconds=0)- return path, "Pipeline image preview complete."+ stage_cache = PreviewStageCache(cache_dir)+ root_key = cache_key({"kind": "source", "mode": mode,+ "source": file_identity(source_path),+ "runtime": _preview_runtime_identity()})+ output_dir = prepare_output_dir(output_dir)+ if mode == "Image":+ output = unique_output_path(output_dir / f"pipeline-preview-{time.time_ns()}.png")+ preview_settings = replace(settings, image_format="PNG", image_quality=100)+ path = render_item(source_path, preview_settings, mode, output, controller, progress,+ preview=True,+ preview_cache=stage_cache, source_cache_key=root_key)+ prune_preview_cache(root=stage_cache.root, protected_keys=stage_cache.used_keys,+ min_idle_seconds=0)+ return path, "Pipeline image preview complete."+ JOBS.mkdir(parents=True, exist_ok=True)with tempfile.TemporaryDirectory(prefix="visual-preview-source-", dir=JOBS) as temp:- clip_key = cache_key({"kind": "source-clip", "source": root_key,- "start_seconds": float(start_seconds),- "clip_seconds": None if clip_seconds is None else float(clip_seconds)})- clip = stage_cache.lookup(clip_key)- if clip is None:- clip_dir = Path(temp) / "source-clip"- clip_dir.mkdir()- clip = _extract_lossless_preview_clip(source_path, clip_dir, controller,- start_seconds, clip_seconds)- if controller.cancel.is_set():- raise Cancelled("Render stopped by user.")- clip = stage_cache.publish(clip_key, clip_dir, clip)- elif progress:- progress(0.0, "Using cached source clip")- output = unique_output_path(output_dir / f"pipeline-preview-{time.time_ns()}.mp4")- render_item(clip, settings, mode, output, controller, progress, preview=True,- preview_cache=stage_cache,- source_cache_key=clip_key)- prune_preview_cache(root=stage_cache.root, protected_keys=stage_cache.used_keys,- min_idle_seconds=0)- return str(output), "Pipeline video preview complete."---def _extract_lossless_preview_clip(source: Path, directory: Path,- controller: JobController, start_seconds: float,- clip_seconds: float | None) -> Path:- """Frame-accurate clip cut without changing pixels before the first card."""- metadata = ffmpeg.probe_video(source, count_mode="metadata", controller=controller)- start = max(0.0, float(start_seconds or 0.0) - 0.002)- fast_seek = max(0.0, start - 2.0)- accurate_seek = max(0.0, start - fast_seek)- output = directory / "source-clip.mkv"- color_args: list[str] = []- for key, flag in (("color_primaries", "-color_primaries"),- ("color_transfer", "-color_trc"),- ("color_space", "-colorspace")):- value = metadata.get(key)- if value and value != "unknown":- color_args.extend((flag, str(value)))- command = [str(FFMPEG), "-hide_banner", "-loglevel", "error", "-y",- "-ss", f"{fast_seek:.6f}", "-i", str(source),- "-ss", f"{accurate_seek:.6f}",- *(["-frames:v", "1"] if clip_seconds is None else- ["-t", f"{float(clip_seconds):.6f}"]),- "-map", "0:v:0", "-map_metadata", "0", "-an",- "-c:v", "ffv1", "-level", "3", "-pix_fmt", "gbrp10le",- *color_args, str(output)]- _run_command(command, controller, "Preview clip extraction")- return output+ clip_key = cache_key({"kind": "source-clip", "source": root_key,+ "start_seconds": float(start_seconds),+ "clip_seconds": None if clip_seconds is None else float(clip_seconds)})+ clip = stage_cache.lookup(clip_key)+ if clip is None:+ clip_dir = Path(temp) / "source-clip"+ clip_dir.mkdir()+ clip = _extract_lossless_preview_clip(source_path, clip_dir, controller,+ start_seconds, clip_seconds)+ if controller.cancel.is_set():+ raise Cancelled("Render stopped by user.")+ clip = stage_cache.publish(clip_key, clip_dir, clip)+ elif progress:+ progress(0.0, "Using cached source clip")+ output = unique_output_path(output_dir / f"pipeline-preview-{time.time_ns()}.mkv")+ output = render_item(clip, settings, mode, output, controller, progress, preview=True,+ preview_cache=stage_cache,+ source_cache_key=clip_key)+ prune_preview_cache(root=stage_cache.root, protected_keys=stage_cache.used_keys,+ min_idle_seconds=0)+ if clip_seconds is None:+ return decode_preview_frame(output, controller=controller), "Pipeline frame preview complete."+ return str(output), "Pipeline video preview complete (lossless cached clip)."+++def _extract_lossless_preview_clip(source: Path, directory: Path,+ controller: JobController, start_seconds: float,+ clip_seconds: float | None) -> Path:+ """Frame-accurate clip cut without changing pixels before the first card."""+ return Path(extract_preview_subclip(+ source, dest_dir=directory, controller=controller,+ start_seconds=start_seconds, length_seconds=clip_seconds,+ single_frame=clip_seconds is None))diff --git a/src/frame_interpolation/models.py b/src/frame_interpolation/models.pyindex 49da98e..b8ceee9 100644--- a/src/frame_interpolation/models.py+++ b/src/frame_interpolation/models.py@@ -1,148 +1,145 @@-from __future__ import annotations--from dataclasses import dataclass, field-from fractions import Fraction---FPS_RATES: dict[str, Fraction] = {- "23.976": Fraction(24000, 1001),- "25": Fraction(25, 1),- "29.97": Fraction(30000, 1001),- "30": Fraction(30, 1),- "50": Fraction(50, 1),- "59.94": Fraction(60000, 1001),- "60": Fraction(60, 1),- "90": Fraction(90, 1),- "119.88": Fraction(120000, 1001),- "120": Fraction(120, 1),- "144": Fraction(144, 1),- "165": Fraction(165, 1),- "180": Fraction(180, 1),- "240": Fraction(240, 1),- "360": Fraction(360, 1),- "480": Fraction(480, 1),-}-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:- if isinstance(value, Fraction):- rate = value- else:- key = str(value).strip()- try:- rate = FPS_RATES[key]- except KeyError as exc:- choices = ", ".join(FPS_CHOICES)- raise ValueError(f"Unsupported output FPS {value!r}. Choose one of: {choices}.") from exc- if rate <= 0:- raise ValueError("Output FPS must be positive.")- return rate---@dataclass(slots=True)-class FrameInterpolationOptions:- ai_gpu_uuid: str = "auto"- video_gpu_uuid: str = "auto"- target_fps: str = "60"- engine: str = "Auto"- codec: str = "H.264 (NVIDIA NVENC)"- container: str = "MP4"- quality: str = "Auto (Default)"- hdr_mode: bool = False- rename_mode: str = "Auto"- custom_suffix: str = "_Frame_Interpolation"- preview_seconds: float | None = None- # True = truncated preview uses the forced H.264 SDR path (current behavior).- # False = truncated preview uses the user's codec/container (HDR preserved).- preview_compat: bool = True-- @property- def target_rate(self) -> Fraction:- return resolve_target_rate(self.target_fps)---@dataclass(slots=True)-class FrameInterpolationCapabilities:- available: bool- gpu: str- driver: str- hags_enabled: bool- native_generated_frame_max: int- native_multiplier: int- cascade_available: bool- runtime_version: str- bridge_version: str- bridge_abi_version: int- nvof_available: bool- cuda_interop: bool- signature_status: str- detail: str = ""- gpu_uuid: str = "auto"---@dataclass(frozen=True, slots=True)-class InterpolationPlan:- path: str- source_rate: Fraction- target_rate: Fraction- native_multiplier: int- grid_multiplier: int- cascade_stages: int- maximum_temporal_error: Fraction- generated_per_interval: int---@dataclass(slots=True)-class FrameInterpolationResult:- output_path: str- report_path: str- selected_path: str- native_multiplier: int- cascade_stages: int- copied_frames: int- generated_frames: int- dropped_frames: int- output_frames: int- maximum_temporal_approximation_seconds: float- scene_cuts: int- elapsed_seconds: float- timings: dict[str, float] = field(default_factory=dict)- bridge_version: str = ""- bridge_abi_version: int = 0- nvof_available: bool = False- memory_path: str = ""- decode_backend: str = ""- encode_backend: str = ""- upload_bytes: int = 0- download_bytes: int = 0- surface_pool_pressure: dict[str, int] = field(default_factory=dict)- diagnostics: dict = field(default_factory=dict)---@dataclass(slots=True)-class FrameInterpolationSuccess:- index: int- input_path: str- result: FrameInterpolationResult---@dataclass(slots=True)-class FrameInterpolationFailure:- index: int- input_path: str- error: str- cancelled: bool = False---@dataclass(slots=True)-class FrameInterpolationBatchResult:- successes: list[FrameInterpolationSuccess]- failures: list[FrameInterpolationFailure]- cancelled: bool- manifest_path: str+from __future__ import annotations++from dataclasses import dataclass, field+from fractions import Fraction+++FPS_RATES: dict[str, Fraction] = {+ "23.976": Fraction(24000, 1001),+ "25": Fraction(25, 1),+ "29.97": Fraction(30000, 1001),+ "30": Fraction(30, 1),+ "50": Fraction(50, 1),+ "59.94": Fraction(60000, 1001),+ "60": Fraction(60, 1),+ "90": Fraction(90, 1),+ "119.88": Fraction(120000, 1001),+ "120": Fraction(120, 1),+ "144": Fraction(144, 1),+ "165": Fraction(165, 1),+ "180": Fraction(180, 1),+ "240": Fraction(240, 1),+ "360": Fraction(360, 1),+ "480": Fraction(480, 1),+}+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 = ("1", "3", "5", "10", "20", "30")+PREVIEW_LENGTH_DEFAULT = "3"+++def resolve_target_rate(value: str | int | float | Fraction) -> Fraction:+ if isinstance(value, Fraction):+ rate = value+ else:+ key = str(value).strip()+ try:+ rate = FPS_RATES[key]+ except KeyError as exc:+ choices = ", ".join(FPS_CHOICES)+ raise ValueError(f"Unsupported output FPS {value!r}. Choose one of: {choices}.") from exc+ if rate <= 0:+ raise ValueError("Output FPS must be positive.")+ return rate+++@dataclass(slots=True)+class FrameInterpolationOptions:+ ai_gpu_uuid: str = "auto"+ video_gpu_uuid: str = "auto"+ target_fps: str = "60"+ engine: str = "Auto"+ codec: str = "H.264"+ container: str = "MP4"+ quality: str = "Auto (Default)"+ hdr_mode: bool = False+ rename_mode: str = "Auto"+ custom_suffix: str = "_Frame_Interpolation"+ preview_seconds: float | None = None++ @property+ def target_rate(self) -> Fraction:+ return resolve_target_rate(self.target_fps)+++@dataclass(slots=True)+class FrameInterpolationCapabilities:+ available: bool+ gpu: str+ driver: str+ hags_enabled: bool+ native_generated_frame_max: int+ native_multiplier: int+ cascade_available: bool+ runtime_version: str+ bridge_version: str+ bridge_abi_version: int+ nvof_available: bool+ cuda_interop: bool+ signature_status: str+ detail: str = ""+ gpu_uuid: str = "auto"+++@dataclass(frozen=True, slots=True)+class InterpolationPlan:+ path: str+ source_rate: Fraction+ target_rate: Fraction+ native_multiplier: int+ grid_multiplier: int+ cascade_stages: int+ maximum_temporal_error: Fraction+ generated_per_interval: int+++@dataclass(slots=True)+class FrameInterpolationResult:+ output_path: str+ report_path: str+ selected_path: str+ native_multiplier: int+ cascade_stages: int+ copied_frames: int+ generated_frames: int+ dropped_frames: int+ output_frames: int+ maximum_temporal_approximation_seconds: float+ scene_cuts: int+ elapsed_seconds: float+ timings: dict[str, float] = field(default_factory=dict)+ bridge_version: str = ""+ bridge_abi_version: int = 0+ nvof_available: bool = False+ memory_path: str = ""+ decode_backend: str = ""+ encode_backend: str = ""+ upload_bytes: int = 0+ download_bytes: int = 0+ surface_pool_pressure: dict[str, int] = field(default_factory=dict)+ diagnostics: dict = field(default_factory=dict)+++@dataclass(slots=True)+class FrameInterpolationSuccess:+ index: int+ input_path: str+ result: FrameInterpolationResult+++@dataclass(slots=True)+class FrameInterpolationFailure:+ index: int+ input_path: str+ error: str+ cancelled: bool = False+++@dataclass(slots=True)+class FrameInterpolationBatchResult:+ successes: list[FrameInterpolationSuccess]+ failures: list[FrameInterpolationFailure]+ cancelled: bool+ manifest_path: strdiff --git a/src/frame_interpolation/preview.py b/src/frame_interpolation/preview.pyindex 5b074eb..73c7430 100644--- a/src/frame_interpolation/preview.py+++ b/src/frame_interpolation/preview.py@@ -4,10 +4,7 @@ from dataclasses import replacefrom pathlib import Pathfrom ..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 ..core.ffmpeg.preview import LOSSLESS_PREVIEW_CODECfrom ..settings.storage import processing_gpu_settingsfrom .capabilities import probe_frame_interpolation_capabilitiesfrom .models import FrameInterpolationOptions@@ -87,7 +84,6 @@ def preview_frame_interpolation_native(input_path: str,options: FrameInterpolationOptions,*,- preview_encoding: str = "Auto",progress=None,output_dir=None,controller=None,@@ -113,55 +109,32 @@ def preview_frame_interpolation_native(frame_no = 1effective_path = str(input_path)temp_clip: str | None = None- if start > 0.05:+ if start > 0:from ..core.ffmpeg.preview import extract_preview_subcliptemp_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(- options.codec, options.container, preview_encoding_mode- )- compat_preview = wants_compat_preview(options.codec, options.container, preview_encoding_mode)- effective = replace(- options,- codec=effective_codec,- container=effective_container,- hdr_mode=(options.hdr_mode and not compat_preview),- preview_seconds=length_seconds,- preview_compat=compat_preview,- )- 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_encoding_mode == "Auto" and not compat_preview:- try:- playable = is_browser_playable(result.output_path)- except Exception:- playable = False- if not playable:+ try:+ effective = replace(+ options,+ codec=LOSSLESS_PREVIEW_CODEC,+ container="MKV",+ quality="Auto (Default)",+ hdr_mode=bool(options.hdr_mode or probe_video(effective_path, count_mode="metadata", controller=controller).get("hdr")),+ preview_seconds=length_seconds,+ )+ result = interpolate_video(+ effective_path, effective, progress, output_dir=output_dir, controller=controller)+ finally:+ if temp_clip:try:- 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, (+ Path(temp_clip).unlink(missing_ok=True)+ except OSError:+ pass+ return result.output_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}{derived_note}"+ f"frames in {result.elapsed_seconds:.1f}s. Cached clip: {result.output_path}\nReport: {result.report_path}")diff --git a/src/frame_interpolation/processor.py b/src/frame_interpolation/processor.pyindex ed34c3f..ff39ab2 100644--- a/src/frame_interpolation/processor.py+++ b/src/frame_interpolation/processor.py@@ -1,827 +1,802 @@-from __future__ import annotations--import gc-import math-import os-import queue-import tempfile-import threading-import time-from contextlib import nullcontext, suppress-from dataclasses import dataclass, replace-from fractions import Fraction-from pathlib import Path-from typing import Any, Callable--import av-import numpy as np-from av.codec.hwaccel import HWAccel-from av.video.reformatter import Colorspace--from ..core import app_log, ffmpeg-from ..core.disk_paths import OutputFile, prepare_output_dir-from ..core.gpu_selection import resolve_runtime_ai_gpu-from ..core.jobs import Cancelled, active_job-from ..core.naming import output_filename, unique_output_path, validate_rename-from ..core.paths import JOBS, OUTPUTS-from ..core.runtime import prepare_runtime, rotate_frame-from ..upscale.video.cuda_transfer import CudaTransferPool-from .capabilities import probe_frame_interpolation_capabilities-from .models import FrameInterpolationOptions, FrameInterpolationResult-from .native import DLSSGCudaSurface, DirectDLSSGSession-from .scheduler import choose_interpolation_plan, output_frame_count--_BATCH_CONTEXT = threading.local()-_END = object()-_NVENC = {- "H.264 (NVIDIA NVENC)": "h264_nvenc",- "H.265 (NVIDIA NVENC)": "hevc_nvenc",- "AV1 (NVIDIA NVENC)": "av1_nvenc",-}---@dataclass(slots=True)-class TimedFrame:- bridge_frame: Any- encode_frame: Any- timestamp: Fraction- segment: int- provenance: str- source_index: int | None = None---@dataclass(slots=True)-class _Encoder:- name: str- display: str- pixel_format: str- cuda_input: bool- options: dict[str, str]- bitrate: int---def _is_nvenc(codec: str) -> bool:- return ffmpeg._normalize_codec(codec) in _NVENC---def automatic_cuda_path(codec: str, rotation: int | float = 0) -> bool:- """Select the fastest valid transport without a user-facing mode switch."""- return _is_nvenc(codec) and not bool(rotation)---def _codec_available(name: str) -> bool:- try:- av.codec.Codec(name, "w")- return True- except Exception:- return False---def _encoder(options: FrameInterpolationOptions, codec: str, width: int, height: int,- rate: Fraction, hdr: bool, cuda_input: bool, ordinal: int) -> _Encoder:- normalized = ffmpeg._normalize_codec(codec)- quality = ffmpeg.resolve_encoding_quality(- options.quality, codec, width, height, float(rate), hdr_mode=hdr)- bitrate = int(quality.get("target_bitrate_kbps") or 0) * 1000- if normalized in _NVENC:- name = _NVENC[normalized]- values = {"preset": "p6", "rc": "vbr", "gpu": str(ordinal),- "rc-lookahead": "0", "surfaces": "8", "delay": "3"}- if name != "av1_nvenc":- values["tune"] = "hq"- if quality["mode"] == "constant-quality":- values["cq"] = "0"- bitrate = 0- return _Encoder(name, name, "cuda" if cuda_input else ("p010le" if hdr else "nv12"),- cuda_input, values, bitrate)- common = {"crf": "0"} if quality["mode"] == "constant-quality" else {}- if normalized == "H.264":- return _Encoder("libx264", "libx264", "yuv420p", False,- {"preset": "slow", **common}, bitrate)- if normalized in {"H.265", "HEVC"}:- return _Encoder("libx265", "libx265", "yuv420p10le" if hdr else "yuv420p",- False, {"preset": "slow", **common}, bitrate)- if normalized == "AV1":- name = "libsvtav1" if _codec_available("libsvtav1") else "libaom-av1"- if not _codec_available(name):- raise RuntimeError("No in-process CPU AV1 encoder is available.")- values = ({"preset": "6"} if name == "libsvtav1" else {"cpu-used": "4"})- values.update(common)- return _Encoder(name, name, "yuv420p10le" if hdr else "yuv420p", False, values, bitrate)- if normalized == "ProRes Proxy":- values = {"profile": "0"}- bits_per_mb = quality.get("bits_per_mb")- if bits_per_mb is None and options.quality == "Auto (Default)":- bits_per_mb = 300- if bits_per_mb is not None:- values["bits_per_mb"] = str(int(bits_per_mb))- return _Encoder("prores_ks", "prores_ks (Proxy)", "yuv422p10le", False, values, 0)- if normalized == "ProRes HQ":- return _Encoder("prores_ks", "prores_ks (HQ)", "yuv422p10le", False,- {"profile": "3"}, 0)- if normalized == "FFV1 Lossless RGB 10-bit":- return _Encoder("ffv1", "ffv1 (Lossless RGB 10-bit)", "gbrp10le", False,- {"level": "3", "slicecrc": "1"}, 0)- raise ValueError(f"Unsupported in-process codec: {codec}.")---def _matrix_code(metadata: dict[str, Any], *, hdr: bool = False) -> int:- value = str(metadata.get("color_space") or "").casefold()- if value in {"bt2020nc", "bt2020c"}:- return 2- if value in {"bt470bg", "smpte170m"}:- return 0- if value == "bt709":- return 1- if value == "fcc":- return 3- if value == "smpte240m":- return 4- # FFmpeg decodes untagged SDR YUV to RGB with its BT.601 default. Match- # that interpretation when the RGB pixels return to an encoded YUV frame.- return 2 if hdr else 0---def _range_code(metadata: dict[str, Any]) -> int:- return int(str(metadata.get("color_range") or "").casefold() in {"pc", "jpeg", "full"})---def _primaries_code(metadata: dict[str, Any]) -> int:- value = str(metadata.get("color_primaries") or "").casefold()- return 2 if value == "bt2020" else 0 if value in {"bt470bg", "bt470m", "smpte170m"} else 1---def _transfer_code(metadata: dict[str, Any]) -> int:- return {"iec61966-2-1": 1, "srgb": 1, "gamma22": 2, "bt470m": 2,- "gamma28": 3, "bt470bg": 3, "linear": 4}.get(- str(metadata.get("color_transfer") or "").casefold(), 0)---def _set_color_properties(context: Any, metadata: dict[str, Any], hdr: bool) -> None:- primaries = str(metadata.get("color_primaries") or "").casefold()- transfer = str(metadata.get("color_transfer") or "").casefold()- matrix = str(metadata.get("color_space") or "").casefold()- context.color_primaries = {"bt709": 1, "bt470m": 4, "bt470bg": 5,- "smpte170m": 6, "smpte240m": 7, "bt2020": 9,- "smpte432": 12}.get(primaries, 2)- context.color_trc = {"bt709": 1, "bt470m": 4, "bt470bg": 5,- "smpte170m": 6, "smpte240m": 7, "linear": 8, "iec61966-2-1": 13,- "smpte2084": 16, "arib-std-b67": 18}.get(transfer, 2)- context.colorspace = {"bt709": 1, "fcc": 4, "bt470bg": 5,- "smpte170m": 6, "smpte240m": 7, "bt2020nc": 9,- "bt2020c": 10}.get(matrix, 9 if hdr else 6)- context.color_range = 2 if _range_code(metadata) else 1- if hdr and primaries in {"", "unknown"}:- context.color_primaries, context.color_trc, context.colorspace = 9, 16, 9---def _put(target: queue.Queue, item: Any, stop: threading.Event,- controller: Any, failures: list[BaseException]) -> None:- while not stop.is_set():- if controller.cancel.is_set():- stop.set()- raise Cancelled("Frame interpolation stopped by user.")- if failures:- stop.set()- raise failures[0]- try:- target.put(item, timeout=0.05)- return- except queue.Full:- continue- raise failures[0] if failures else Cancelled("Frame interpolation stopped by user.")---def _get(source: queue.Queue, stop: threading.Event,- controller: Any, failures: list[BaseException]) -> Any:- while True:- if controller.cancel.is_set():- stop.set()- raise Cancelled("Frame interpolation stopped by user.")- if failures:- stop.set()- raise failures[0]- try:- return source.get(timeout=0.05)- except queue.Empty:- if stop.is_set():- raise failures[0] if failures else Cancelled("Frame interpolation stopped by user.")---def _validate_decoded_frame(frame: Any) -> Any:- if bool(getattr(frame, "is_corrupt", False)):- raise RuntimeError("The video decoder returned a corrupt frame.")- return frame---class DLSSGStage:- def __init__(self, session: DirectDLSSGSession, generated_count: int, *,- detect_source_cuts: bool, cuda_output: bool, output_p010: bool,- colors: dict[str, int], preserve_source_rgb: bool = False) -> None:- self.session, self.generated_count = session, int(generated_count)- self.detect_source_cuts, self.cuda_output = detect_source_cuts, cuda_output- self.output_p010, self.colors = output_p010, colors- self.preserve_source_rgb = preserve_source_rgb- self.previous: TimedFrame | None = None- self.scene_cuts = self.duplicates = 0-- def push(self, frame: TimedFrame) -> list[TimedFrame]:- previous = self.previous- force_reset = previous is not None and frame.segment != previous.segment- bridge_frame = frame.bridge_frame- if (isinstance(bridge_frame, av.VideoFrame)- and bridge_frame.format.name not in {"cuda", "p010", "p010le"}):- bridge_frame = np.ascontiguousarray(bridge_frame.to_ndarray(format="rgba"))- generated, detail = self.session.process_frame(- bridge_frame, force_reset=force_reset,- detect_scene_cut=self.detect_source_cuts, output_cuda=self.cuda_output,- output_p010=self.output_p010, output_rgb=True, **self.colors)- if self.preserve_source_rgb:- source_rgb = self.session.copy_current_input_rgb()- frame = replace(frame, bridge_frame=source_rgb, encode_frame=source_rgb)- if previous is not None and detail["scene_cut"] and self.detect_source_cuts:- frame = replace(frame, segment=previous.segment + 1)- self.scene_cuts += 1- self.duplicates += int(previous is not None and detail["duplicate"])- output: list[TimedFrame] = []- if previous is not None and not detail["reset"]:- interval = frame.timestamp - previous.timestamp- for index, pixels in enumerate(generated, start=1):- output.append(TimedFrame(- pixels, pixels,- previous.timestamp + interval * Fraction(index, self.generated_count + 1),- frame.segment, "DLSSG"))- self.previous = frame- output.append(frame)- return output---class NearestTimestampWriter:- def __init__(self, target_rate: Fraction, output_count: int,- emit: Callable[[TimedFrame, int], None]) -> None:- self.target_rate, self.output_count, self.emit = target_rate, int(output_count), emit- self.next_index = 0- self.previous: TimedFrame | None = None- self.tie_late = False- self.copied = self.generated = 0- self.max_error = Fraction(0)- self.selected_real_ids: set[int] = set()-- def _write(self, frame: TimedFrame, ideal: Fraction) -> None:- self.emit(frame, self.next_index)- self.max_error = max(self.max_error, abs(frame.timestamp - ideal))- if frame.provenance == "DLSSG":- self.generated += 1- else:- self.copied += 1- if frame.source_index is not None:- self.selected_real_ids.add(frame.source_index)- self.next_index += 1-- def push(self, current: TimedFrame) -> None:- if self.previous is None:- self.previous = current- return- midpoint = (self.previous.timestamp + current.timestamp) / 2- while self.next_index < self.output_count:- ideal = Fraction(self.next_index, 1) / self.target_rate- if ideal < midpoint:- self._write(self.previous, ideal)- elif ideal == midpoint:- self._write(current if self.tie_late else self.previous, ideal)- self.tie_late = not self.tie_late- else:- break- self.previous = current-- def finish(self) -> None:- if self.previous is None:- raise ValueError("The input video contains no decodable frames.")- while self.next_index < self.output_count:- self._write(self.previous, Fraction(self.next_index, 1) / self.target_rate)---def _duration_fraction(metadata: dict, source_rate: Fraction, frames: int, *, cfr: bool) -> Fraction:- if cfr and frames > 0:- return Fraction(frames, 1) / source_rate- return Fraction(str(metadata.get("video_stream_duration") or metadata["duration"]))---def _validate(options: FrameInterpolationOptions) -> None:- _ = options.target_rate- validate_rename(options.rename_mode, options.custom_suffix)- ffmpeg.validate_codec_container(options.codec, options.container)- if options.hdr_mode and not ffmpeg.hdr_mode_supported(options.codec):- raise ValueError(f"HDR Mode is unavailable for {options.codec!r}.")- if options.preview_seconds is not None and (- not math.isfinite(float(options.preview_seconds)) or float(options.preview_seconds) <= 0):- raise ValueError("Preview duration must be positive.")---def interpolate_video(- input_path: str | os.PathLike[str], options: FrameInterpolationOptions | None = None,- progress: Callable[[float, str], None] | None = None, *,- output_dir: str | os.PathLike[str] | None = None, controller=None,-) -> FrameInterpolationResult:- operation_started = time.perf_counter()- options = replace(options) if options is not None else FrameInterpolationOptions()- options.container = ffmpeg.container_for_codec(options.codec)- _validate(options)- source = Path(input_path).resolve()- if not source.is_file():- raise FileNotFoundError(source)- runtime_started = time.perf_counter()- runtime = prepare_runtime()- runtime_prepare_seconds = time.perf_counter() - runtime_started- ai_gpu = resolve_runtime_ai_gpu(runtime.gpus, runtime.runtime_bundle, options.ai_gpu_uuid)- capability_started = time.perf_counter()- capabilities = probe_frame_interpolation_capabilities(options.ai_gpu_uuid)- capability_probe_seconds = time.perf_counter() - capability_started- if not capabilities.available:- raise RuntimeError("Direct NVIDIA DLSS Frame Generation is unavailable. " + capabilities.detail)- prepared_controller = getattr(_BATCH_CONTEXT, "controller", None)- job_context = nullcontext(prepared_controller) if prepared_controller is not None else active_job(controller)- with job_context as controller:- assert controller is not None- started = time.perf_counter()-- def update(value: float, message: str) -> None:- if controller.cancel.is_set():- raise Cancelled("Frame interpolation stopped by user.")- if progress:- value = max(0.0, min(1.0, float(value)))- # Status bar shows only the main status; no ETA suffix.- progress(value, message)-- output_file: OutputFile | None = None- decoded_container: Any | None = None- encoded_container: Any | None = None- decode_thread: threading.Thread | None = None- encode_thread: threading.Thread | None = None- sessions: list[DirectDLSSGSession] = []- transfer_pool: CudaTransferPool | None = None- job: tempfile.TemporaryDirectory[str] | None = None- stop, decode_stop = threading.Event(), threading.Event()- failures: list[BaseException] = []- timings: dict[str, float] = {- "preflight_seconds": time.perf_counter() - operation_started,- "runtime_prepare_seconds": runtime_prepare_seconds,- "capability_probe_seconds": capability_probe_seconds,- "session_initialization_seconds": 0.0,- "probe_seconds": 0.0, "decode_seconds": 0.0, "software_prepare_seconds": 0.0,- "bridge_input_seconds": 0.0, "optical_flow_seconds": 0.0,- "dlssg_seconds": 0.0, "bridge_output_seconds": 0.0,- "encode_seconds": 0.0, "cross_gpu_seconds": 0.0,- }- try:- probe_start = time.perf_counter()- metadata = ffmpeg.probe_video(- source, count_mode="metadata", inspect_timestamps=True)- source_rate = Fraction(metadata["rate"])- cfr = bool(metadata.get("cfr", True))- source_frames = int(metadata["frames"])- if source_frames <= 0:- source_frames = int(ffmpeg.probe_video(source, count_mode="exact")["frames"])- duration = _duration_fraction(metadata, source_rate, source_frames, cfr=cfr)- preview = options.preview_seconds is not None- compat_preview = preview and bool(options.preview_compat)- effective_hdr = bool(options.hdr_mode and not compat_preview)- if metadata["hdr"] and not effective_hdr:- raise ValueError("HDR input requires Frame Interpolation HDR Mode with a 10-bit codec.")- if preview:- duration = min(duration, Fraction(str(options.preview_seconds)))- source_frames = min(source_frames, ffmpeg.preview_frame_count(source, float(duration)))- duration = min(duration, Fraction(source_frames, 1) / source_rate)- plan = choose_interpolation_plan(- source_rate, options.target_rate, options.engine,- capabilities.native_multiplier, cfr=cfr)- output_count = output_frame_count(duration, options.target_rate)- timings["probe_seconds"] = time.perf_counter() - probe_start- update(.01, "Preparing frame interpolation")-- selected_codec = "H.264 (NVIDIA NVENC)" if compat_preview else options.codec- video_gpu = ffmpeg.resolve_video_gpu(- runtime.gpus, options.video_gpu_uuid, selected_codec,- int(metadata["width"]), int(metadata["height"]))- if _is_nvenc(selected_codec) and video_gpu is None:- raise RuntimeError("The selected NVENC codec has no available encoding GPU.")- ai_ordinal = int(ai_gpu["cuda_ordinal"])- encode_ordinal = int(video_gpu["cuda_ordinal"]) if video_gpu is not None else ai_ordinal- # The processing path is automatic, matching Upscale: an NVENC- # output keeps decode/interpolation/encode on CUDA, while a CPU- # codec uses the in-process host-staging ABI.- want_cuda = automatic_cuda_path(selected_codec, metadata["rotation"])- decode_device = HWAccel(- "cuda", device=str(ai_ordinal), allow_software_fallback=True,- options={"primary_ctx": "1"}, is_hw_owned=True) if want_cuda else None- decoded_container = av.open(str(source), hwaccel=decode_device)- input_stream = decoded_container.streams.video[0]- input_stream.thread_type = "AUTO"- decoder = iter(decoded_container.decode(input_stream))- tick = time.perf_counter()- try:- first_frame = _validate_decoded_frame(next(decoder))- except StopIteration as exc:- raise ValueError("The input contains no decodable video frames.") from exc- timings["decode_seconds"] += time.perf_counter() - tick- cuda_route = bool(want_cuda and first_frame.format.name == "cuda")- decode_backend = "nvdec" if cuda_route else "software"- output_p010 = bool(effective_hdr)- encoder = _encoder(options, selected_codec, int(metadata["width"]),- int(metadata["height"]), options.target_rate,- effective_hdr, cuda_route, encode_ordinal)-- destination = prepare_output_dir(output_dir, default=OUTPUTS)- stamp = time.strftime("%Y%m%d-%H%M%S") + f"-{time.time_ns()%1_000_000:06d}"- extension = {"MP4": ".mp4", "MKV": ".mkv", "MOV": ".mov"}[options.container]- output = unique_output_path(destination / output_filename(- source, extension, options.rename_mode, options.custom_suffix,- f"{source.stem}_{'DLSSFG_PREVIEW' if preview else 'DLSSFG'}_{stamp}"))- output_file = OutputFile(output)- JOBS.mkdir(exist_ok=True)- job = tempfile.TemporaryDirectory(prefix="dlssg-bridge-", dir=JOBS)- try:- temp_video = Path(job.name) / ("encoded.mov" if options.container == "MOV" else- "encoded.mkv" if options.container == "MKV" else "encoded.mp4")- encoded_container = av.open(str(temp_video), mode="w")- encode_device = HWAccel(- "cuda", device=str(encode_ordinal), options={"primary_ctx": "1"},- is_hw_owned=True) if cuda_route else None- output_stream = encoded_container.add_stream(- encoder.name, rate=options.target_rate, hwaccel=encode_device)- output_stream.width, output_stream.height = int(metadata["width"]), int(metadata["height"])- output_stream.pix_fmt = encoder.pixel_format- if cuda_route:- output_stream.codec_context.sw_format = "p010le" if output_p010 else "nv12"- output_tb = Fraction(1, 1) / options.target_rate- output_stream.time_base = output_tb- output_stream.codec_context.time_base = output_tb- output_stream.codec_context.options = encoder.options- output_stream.codec_context.bit_rate = encoder.bitrate- if encoder.display == "prores_ks (Proxy)" and options.quality == "Auto (Default)":- # Proxy's default quantizer remains visibly softer even with- # the higher macroblock budget. Match its high-quality range.- output_stream.codec_context.qscale = True- output_stream.codec_context.global_quality = 3- _set_color_properties(output_stream.codec_context, metadata, effective_hdr)- if encoder.name == "ffv1":- output_stream.codec_context.colorspace = 0 # RGB, no YUV matrix.- output_stream.codec_context.color_range = 2 # Full range.- output_stream.codec_context.open()-- generated_count = plan.generated_per_interval if plan.path == "Native DLSSG" else 1- session_count = 1 if plan.path == "Native DLSSG" else plan.cascade_stages- initialization_start = time.perf_counter()- for _ in range(session_count):- sessions.append(DirectDLSSGSession(- int(metadata["width"]), int(metadata["height"]), generated_count,- controller, ai_ordinal, hdr=effective_hdr))- timings["session_initialization_seconds"] = time.perf_counter() - initialization_start- colors = {"color_matrix": _matrix_code(metadata, hdr=effective_hdr),- "color_range": _range_code(metadata),- "color_primaries": _primaries_code(metadata),- "color_transfer": _transfer_code(metadata),- "rotation": int(metadata["rotation"])}- stages = [DLSSGStage(- session, generated_count, detect_source_cuts=index == 0,- cuda_output=cuda_route, output_p010=output_p010, colors=colors,- preserve_source_rgb=index == 0)- for index, session in enumerate(sessions)]- if cuda_route and encode_ordinal != ai_ordinal:- transfer_pool = CudaTransferPool(ai_ordinal, encode_ordinal, controller)-- rgb_colorspace = {- 0: Colorspace.ITU601, 1: Colorspace.ITU709,- 2: Colorspace.BT2020, 3: Colorspace.FCC,- 4: Colorspace.SMPTE240M,- }[colors["color_matrix"]]-- decode_queue: queue.Queue = queue.Queue(maxsize=4)- encode_queue: queue.Queue = queue.Queue(maxsize=4)-- def decode_worker() -> None:- try:- _put(decode_queue, first_frame, stop, controller, failures)- while not stop.is_set() and not decode_stop.is_set():- frame_start = time.perf_counter()- try:- frame = next(decoder)- except StopIteration:- timings["decode_seconds"] += time.perf_counter() - frame_start- break- timings["decode_seconds"] += time.perf_counter() - frame_start- _validate_decoded_frame(frame)- _put(decode_queue, frame, stop, controller, failures)- except BaseException as exc:- failures.append(exc); stop.set()- finally:- if not decode_stop.is_set() and not stop.is_set():- with suppress(BaseException):- _put(decode_queue, _END, stop, controller, failures)-- encoded_frames = [0]-- def encode_worker() -> None:- try:- while not stop.is_set():- item = _get(encode_queue, stop, controller, failures)- if item is _END:- break- frame, pts = item- encode_start = time.perf_counter()- if not cuda_route and frame.format.name != encoder.pixel_format:- frame = frame.reformat(- format=encoder.pixel_format,- src_colorspace=rgb_colorspace,- dst_colorspace=rgb_colorspace)- if encoder.name == "ffv1":- frame.color_primaries = output_stream.codec_context.color_primaries- frame.color_trc = output_stream.codec_context.color_trc- frame.colorspace = 0- frame.color_range = 2- frame.pts, frame.time_base, frame.duration = pts, output_tb, 1- for packet in output_stream.encode(frame):- encoded_container.mux(packet)- timings["encode_seconds"] += time.perf_counter() - encode_start- encoded_frames[0] += 1- del frame, item- if not failures and not controller.cancel.is_set():- encode_start = time.perf_counter()- for packet in output_stream.encode():- encoded_container.mux(packet)- timings["encode_seconds"] += time.perf_counter() - encode_start- except BaseException as exc:- failures.append(exc); stop.set()-- decode_thread = threading.Thread(target=decode_worker, name="dlssg-decoder", daemon=True)- encode_thread = threading.Thread(target=encode_worker, name="dlssg-encoder", daemon=True)- decode_thread.start(); encode_thread.start()- pipeline_start = time.perf_counter()- decoded = discontinuities = 0- last_timestamp: Fraction | None = None- origin_timestamp: Fraction | None = None- source_segment = 0- nominal = Fraction(1, 1) / source_rate- source_dimensions = (int(first_frame.width), int(first_frame.height))-- def emit(selected: TimedFrame, index: int) -> None:- frame = selected.encode_frame- if isinstance(frame, DLSSGCudaSurface):- convert_start = time.perf_counter()- if encoder.name == "prores_ks" or not cuda_route:- pixels = frame.to_host_rgb()- if effective_hdr:- # DLSSG returns normalized, transfer-encoded half float RGB.- # Keep the 10-bit precision until the final 4:2:2 conversion.- depth = 10- maximum = (1 << depth) - 1- rgb = np.rint(np.clip(pixels[..., :3].astype(np.float32),- 0.0, 1.0) * maximum).astype(np.uint16)- gbr = np.ascontiguousarray(rgb[..., [1, 2, 0]])- frame = av.VideoFrame.from_ndarray(gbr, format=f"gbrp{depth}le")- else:- frame = av.VideoFrame.from_ndarray(pixels, format="rgba")- else:- yuv = frame.to_yuv_surface(- color_matrix=colors["color_matrix"],- color_range=colors["color_range"], p010=output_p010)- frame = yuv.to_av_frame()- timings["final_color_conversion_seconds"] = (- timings.get("final_color_conversion_seconds", 0.0) +- time.perf_counter() - convert_start)- if transfer_pool is not None:- transfer_start = time.perf_counter()- frame, _detail = transfer_pool.transfer(frame)- timings["cross_gpu_seconds"] += time.perf_counter() - transfer_start- _put(encode_queue, (frame, index), stop, controller, failures)-- writer = NearestTimestampWriter(options.target_rate, output_count, emit)- last_update = 0.0- while decoded < source_frames:- frame = _get(decode_queue, stop, controller, failures)- if frame is _END:- break- if (int(frame.width), int(frame.height)) != source_dimensions:- raise ValueError("Source dimensions changed during decoding.")- raw_timestamp = (Fraction(frame.pts) * Fraction(frame.time_base)- if frame.pts is not None and frame.time_base is not None- else Fraction(decoded, 1) / source_rate)- if origin_timestamp is None:- origin_timestamp = raw_timestamp- timestamp = raw_timestamp - origin_timestamp- if last_timestamp is not None and (- timestamp <= last_timestamp or timestamp - last_timestamp > nominal * 2):- source_segment += 1- discontinuities += 1- last_timestamp = timestamp- if cuda_route:- bridge_frame, encode_frame = frame, frame- else:- prepare_start = time.perf_counter()- if effective_hdr:- if metadata["rotation"]:- rgb10 = rotate_frame(- frame.to_ndarray(format="gbrp10le"),- int(metadata["rotation"]),- )- oriented = av.VideoFrame.from_ndarray(- np.ascontiguousarray(rgb10), format="gbrp10le")- bridge_frame = oriented.reformat(format="p010le")- encode_frame = bridge_frame- else:- bridge_frame = frame.reformat(format="p010le")- encode_frame = frame- else:- rgba = rotate_frame(frame.to_ndarray(format="rgba"), int(metadata["rotation"]))- rgba = np.ascontiguousarray(rgba)- encode_frame = (frame if not metadata["rotation"]- else av.VideoFrame.from_ndarray(rgba, format="rgba"))- bridge_frame = rgba- timings["software_prepare_seconds"] += time.perf_counter() - prepare_start- items = [TimedFrame(bridge_frame, encode_frame, timestamp, source_segment,- "Source", decoded)]- for stage in stages:- next_items: list[TimedFrame] = []- for item in items:- native_start = time.perf_counter()- produced = stage.push(item)- native_elapsed = time.perf_counter() - native_start- next_items.extend(produced)- timings["bridge_total_seconds"] = timings.get("bridge_total_seconds", 0.0) + native_elapsed- items = next_items- for item in items:- writer.push(item)- decoded += 1- del frame, items- now = time.perf_counter()- if now - last_update > .2:- update(.04 + .82 * decoded / max(1, source_frames),- "Interpolating frames")- last_update = now- if decoded != source_frames:- raise RuntimeError(f"Decoded {decoded} source frames; expected {source_frames}.")- writer.finish()- _put(encode_queue, _END, threading.Event(), controller, failures)- decode_stop.set()- # A truncated preview intentionally stops before decoder EOF.- # Free one or more queue slots so a producer already blocked in- # _put can publish its current frame, observe decode_stop, and exit.- while True:- try:- decode_queue.get_nowait()- except queue.Empty:- break- decode_thread.join(timeout=30); encode_thread.join(timeout=300)- if decode_thread.is_alive() or encode_thread.is_alive():- raise RuntimeError("The bounded Frame Interpolation pipeline did not drain.")- if failures:- raise failures[0]- if encoded_frames[0] != output_count:- raise RuntimeError(f"Encoder accepted {encoded_frames[0]} frames; expected {output_count}.")- timings["pipeline_seconds"] = time.perf_counter() - pipeline_start+from __future__ import annotations++import gc+import math+import os+import queue+import tempfile+import threading+import time+from contextlib import nullcontext, suppress+from dataclasses import dataclass, replace+from fractions import Fraction+from pathlib import Path+from typing import Any, Callable++import av+from ..core.ffmpeg.frames import open_video_decoder, VideoOutput+import numpy as np+from av.codec.hwaccel import HWAccel+from av.video.reformatter import Colorspace++from ..core import app_log, ffmpeg+from ..core.disk_paths import OutputFile, prepare_output_dir+from ..core.gpu_selection import resolve_runtime_ai_gpu+from ..core.jobs import Cancelled, active_job+from ..core.naming import output_filename, unique_output_path, validate_rename+from ..core.paths import JOBS, OUTPUTS+from ..core.runtime import prepare_runtime, rotate_frame+from ..upscale.video.cuda_transfer import CudaTransferPool+from .capabilities import probe_frame_interpolation_capabilities+from .models import FrameInterpolationOptions, FrameInterpolationResult+from .native import DLSSGCudaSurface, DirectDLSSGSession+from .scheduler import choose_interpolation_plan, output_frame_count++_BATCH_CONTEXT = threading.local()+_END = object()+_NVENC = {+ "H.264 (NVIDIA NVENC)": "h264_nvenc",+ "H.265 (NVIDIA NVENC)": "hevc_nvenc",+ "AV1 (NVIDIA NVENC)": "av1_nvenc",+}+++@dataclass(slots=True)+class TimedFrame:+ bridge_frame: Any+ encode_frame: Any+ timestamp: Fraction+ segment: int+ provenance: str+ source_index: int | None = None+++@dataclass(slots=True)+class _Encoder:+ name: str+ display: str+ pixel_format: str+ cuda_input: bool+ options: dict[str, str]+ bitrate: int+++def _is_nvenc(codec: str) -> bool:+ return ffmpeg._normalize_codec(codec) in _NVENC+++def automatic_cuda_path(codec: str, rotation: int | float = 0) -> bool:+ """Select the fastest valid transport without a user-facing mode switch."""+ return _is_nvenc(codec) and not bool(rotation)+++def _codec_available(name: str) -> bool:+ from ..core.ffmpeg.vulkan import ffmpeg_encoders+ return name in ffmpeg_encoders()+++def _encoder(options: FrameInterpolationOptions, codec: str, width: int, height: int,+ rate: Fraction, hdr: bool, cuda_input: bool, ordinal: int) -> _Encoder:+ normalized = ffmpeg._normalize_codec(codec)+ quality = ffmpeg.resolve_encoding_quality(+ options.quality, codec, width, height, float(rate), hdr_mode=hdr)+ bitrate = int(quality.get("target_bitrate_kbps") or 0) * 1000+ if normalized in _NVENC:+ name = _NVENC[normalized]+ values = {"preset": "p6", "rc": "vbr", "gpu": str(ordinal),+ "rc-lookahead": "0", "surfaces": "8", "delay": "3"}+ if name != "av1_nvenc":+ values["tune"] = "hq"+ if quality["mode"] == "constant-quality":+ values["cq"] = "0"+ bitrate = 0+ return _Encoder(name, name, "cuda" if cuda_input else ("p010le" if hdr else "nv12"),+ cuda_input, values, bitrate)+ common = {"crf": "0"} if quality["mode"] == "constant-quality" else {}+ if normalized == "H.264":+ return _Encoder("libx264", "libx264", "yuv420p", False,+ {"preset": "slow", **common}, bitrate)+ if normalized in {"H.265", "HEVC"}:+ return _Encoder("libx265", "libx265", "yuv420p10le" if hdr else "yuv420p",+ False, {"preset": "slow", **common}, bitrate)+ if normalized == "AV1":+ name = "libsvtav1" if _codec_available("libsvtav1") else "libaom-av1"+ if not _codec_available(name):+ raise RuntimeError("No in-process CPU AV1 encoder is available.")+ values = ({"preset": "6"} if name == "libsvtav1" else {"cpu-used": "4"})+ values.update(common)+ return _Encoder(name, name, "yuv420p10le" if hdr else "yuv420p", False, values, bitrate)+ if normalized == "ProRes Proxy":+ values = {"profile": "0"}+ bits_per_mb = quality.get("bits_per_mb")+ if bits_per_mb is None and options.quality == "Auto (Default)":+ bits_per_mb = 300+ if bits_per_mb is not None:+ values["bits_per_mb"] = str(int(bits_per_mb))+ return _Encoder("prores_ks", "prores_ks (Proxy)", "yuv422p10le", False, values, 0)+ if normalized == "ProRes HQ":+ return _Encoder("prores_ks", "prores_ks (HQ)", "yuv422p10le", False,+ {"profile": "3"}, 0)+ if normalized == "FFV1 Lossless RGB 10-bit":+ return _Encoder("ffv1", "ffv1 (Lossless RGB 10-bit)", "gbrp10le", False,+ {"level": "3", "slicecrc": "1"}, 0)+ raise ValueError(f"Unsupported in-process codec: {codec}.")+++def _matrix_code(metadata: dict[str, Any], *, hdr: bool = False) -> int:+ value = str(metadata.get("color_space") or "").casefold()+ if value in {"bt2020nc", "bt2020c"}:+ return 2+ if value in {"bt470bg", "smpte170m"}:+ return 0+ if value == "bt709":+ return 1+ if value == "fcc":+ return 3+ if value == "smpte240m":+ return 4+ # FFmpeg decodes untagged SDR YUV to RGB with its BT.601 default. Match+ # that interpretation when the RGB pixels return to an encoded YUV frame.+ return 2 if hdr else 0+++def _range_code(metadata: dict[str, Any]) -> int:+ return int(str(metadata.get("color_range") or "").casefold() in {"pc", "jpeg", "full"})+++def _primaries_code(metadata: dict[str, Any]) -> int:+ value = str(metadata.get("color_primaries") or "").casefold()+ return 2 if value == "bt2020" else 0 if value in {"bt470bg", "bt470m", "smpte170m"} else 1+++def _transfer_code(metadata: dict[str, Any]) -> int:+ return {"iec61966-2-1": 1, "srgb": 1, "gamma22": 2, "bt470m": 2,+ "gamma28": 3, "bt470bg": 3, "linear": 4}.get(+ str(metadata.get("color_transfer") or "").casefold(), 0)+++def _set_color_properties(context: Any, metadata: dict[str, Any], hdr: bool) -> None:+ primaries = str(metadata.get("color_primaries") or "").casefold()+ transfer = str(metadata.get("color_transfer") or "").casefold()+ matrix = str(metadata.get("color_space") or "").casefold()+ context.color_primaries = {"bt709": 1, "bt470m": 4, "bt470bg": 5,+ "smpte170m": 6, "smpte240m": 7, "bt2020": 9,+ "smpte432": 12}.get(primaries, 2)+ context.color_trc = {"bt709": 1, "bt470m": 4, "bt470bg": 5,+ "smpte170m": 6, "smpte240m": 7, "linear": 8, "iec61966-2-1": 13,+ "smpte2084": 16, "arib-std-b67": 18}.get(transfer, 2)+ context.colorspace = {"bt709": 1, "fcc": 4, "bt470bg": 5,+ "smpte170m": 6, "smpte240m": 7, "bt2020nc": 9,+ "bt2020c": 10}.get(matrix, 9 if hdr else 6)+ context.color_range = 2 if _range_code(metadata) else 1+ if hdr and primaries in {"", "unknown"}:+ context.color_primaries, context.color_trc, context.colorspace = 9, 16, 9+++def _put(target: queue.Queue, item: Any, stop: threading.Event,+ controller: Any, failures: list[BaseException]) -> None:+ while not stop.is_set():+ if controller.cancel.is_set():+ stop.set()+ raise Cancelled("Frame interpolation stopped by user.")+ if failures:+ stop.set()+ raise failures[0]+ try:+ target.put(item, timeout=0.05)+ return+ except queue.Full:+ continue+ raise failures[0] if failures else Cancelled("Frame interpolation stopped by user.")+++def _get(source: queue.Queue, stop: threading.Event,+ controller: Any, failures: list[BaseException]) -> Any:+ while True:+ if controller.cancel.is_set():+ stop.set()+ raise Cancelled("Frame interpolation stopped by user.")+ if failures:+ stop.set()+ raise failures[0]+ try:+ return source.get(timeout=0.05)+ except queue.Empty:+ if stop.is_set():+ raise failures[0] if failures else Cancelled("Frame interpolation stopped by user.")+++def _validate_decoded_frame(frame: Any) -> Any:+ if bool(getattr(frame, "is_corrupt", False)):+ raise RuntimeError("The video decoder returned a corrupt frame.")+ return frame+++class DLSSGStage:+ def __init__(self, session: DirectDLSSGSession, generated_count: int, *,+ detect_source_cuts: bool, cuda_output: bool, output_p010: bool,+ colors: dict[str, int], preserve_source_rgb: bool = False) -> None:+ self.session, self.generated_count = session, int(generated_count)+ self.detect_source_cuts, self.cuda_output = detect_source_cuts, cuda_output+ self.output_p010, self.colors = output_p010, colors+ self.preserve_source_rgb = preserve_source_rgb+ self.previous: TimedFrame | None = None+ self.scene_cuts = self.duplicates = 0++ def push(self, frame: TimedFrame) -> list[TimedFrame]:+ previous = self.previous+ force_reset = previous is not None and frame.segment != previous.segment+ bridge_frame = frame.bridge_frame+ if (isinstance(bridge_frame, av.VideoFrame)+ and bridge_frame.format.name not in {"cuda", "p010", "p010le"}):+ bridge_frame = np.ascontiguousarray(bridge_frame.to_ndarray(format="rgba"))+ generated, detail = self.session.process_frame(+ bridge_frame, force_reset=force_reset,+ detect_scene_cut=self.detect_source_cuts, output_cuda=self.cuda_output,+ output_p010=self.output_p010, output_rgb=True, **self.colors)+ if self.preserve_source_rgb:+ source_rgb = self.session.copy_current_input_rgb()+ frame = replace(frame, bridge_frame=source_rgb, encode_frame=source_rgb)+ if previous is not None and detail["scene_cut"] and self.detect_source_cuts:+ frame = replace(frame, segment=previous.segment + 1)+ self.scene_cuts += 1+ self.duplicates += int(previous is not None and detail["duplicate"])+ output: list[TimedFrame] = []+ if previous is not None and not detail["reset"]:+ interval = frame.timestamp - previous.timestamp+ for index, pixels in enumerate(generated, start=1):+ output.append(TimedFrame(+ pixels, pixels,+ previous.timestamp + interval * Fraction(index, self.generated_count + 1),+ frame.segment, "DLSSG"))+ self.previous = frame+ output.append(frame)+ return output+++class NearestTimestampWriter:+ def __init__(self, target_rate: Fraction, output_count: int,+ emit: Callable[[TimedFrame, int], None]) -> None:+ self.target_rate, self.output_count, self.emit = target_rate, int(output_count), emit+ self.next_index = 0+ self.previous: TimedFrame | None = None+ self.tie_late = False+ self.copied = self.generated = 0+ self.max_error = Fraction(0)+ self.selected_real_ids: set[int] = set()++ def _write(self, frame: TimedFrame, ideal: Fraction) -> None:+ self.emit(frame, self.next_index)+ self.max_error = max(self.max_error, abs(frame.timestamp - ideal))+ if frame.provenance == "DLSSG":+ self.generated += 1+ else:+ self.copied += 1+ if frame.source_index is not None:+ self.selected_real_ids.add(frame.source_index)+ self.next_index += 1++ def push(self, current: TimedFrame) -> None:+ if self.previous is None:+ self.previous = current+ return+ midpoint = (self.previous.timestamp + current.timestamp) / 2+ while self.next_index < self.output_count:+ ideal = Fraction(self.next_index, 1) / self.target_rate+ if ideal < midpoint:+ self._write(self.previous, ideal)+ elif ideal == midpoint:+ self._write(current if self.tie_late else self.previous, ideal)+ self.tie_late = not self.tie_late+ else:+ break+ self.previous = current++ def finish(self) -> None:+ if self.previous is None:+ raise ValueError("The input video contains no decodable frames.")+ while self.next_index < self.output_count:+ self._write(self.previous, Fraction(self.next_index, 1) / self.target_rate)+++def _duration_fraction(metadata: dict, source_rate: Fraction, frames: int, *, cfr: bool) -> Fraction:+ if cfr and frames > 0:+ return Fraction(frames, 1) / source_rate+ return Fraction(str(metadata.get("video_stream_duration") or metadata["duration"]))+++def _validate(options: FrameInterpolationOptions) -> None:+ _ = options.target_rate+ validate_rename(options.rename_mode, options.custom_suffix)+ ffmpeg.validate_codec_container(options.codec, options.container)+ if options.hdr_mode and not ffmpeg.hdr_mode_supported(options.codec):+ raise ValueError(f"HDR Mode is unavailable for {options.codec!r}.")+ if options.preview_seconds is not None and (+ not math.isfinite(float(options.preview_seconds)) or float(options.preview_seconds) <= 0):+ raise ValueError("Preview duration must be positive.")+++def interpolate_video(+ input_path: str | os.PathLike[str], options: FrameInterpolationOptions | None = None,+ progress: Callable[[float, str], None] | None = None, *,+ output_dir: str | os.PathLike[str] | None = None, controller=None,+) -> FrameInterpolationResult:+ operation_started = time.perf_counter()+ options = replace(options) if options is not None else FrameInterpolationOptions()+ _validate(options)+ source = Path(input_path).resolve()+ if not source.is_file():+ raise FileNotFoundError(source)+ runtime_started = time.perf_counter()+ runtime = prepare_runtime()+ runtime_prepare_seconds = time.perf_counter() - runtime_started+ ai_gpu = resolve_runtime_ai_gpu(runtime.gpus, runtime.runtime_bundle, options.ai_gpu_uuid)+ capability_started = time.perf_counter()+ capabilities = probe_frame_interpolation_capabilities(options.ai_gpu_uuid)+ capability_probe_seconds = time.perf_counter() - capability_started+ if not capabilities.available:+ raise RuntimeError("Direct NVIDIA DLSS Frame Generation is unavailable. " + capabilities.detail)+ prepared_controller = getattr(_BATCH_CONTEXT, "controller", None)+ job_context = nullcontext(prepared_controller) if prepared_controller is not None else active_job(controller)+ with job_context as controller:+ assert controller is not None+ started = time.perf_counter()++ def update(value: float, message: str) -> None:+ if controller.cancel.is_set():+ raise Cancelled("Frame interpolation stopped by user.")+ if progress:+ value = max(0.0, min(1.0, float(value)))+ # Status bar shows only the main status; no ETA suffix.+ progress(value, message)++ output_file: OutputFile | None = None+ decoded_container: Any | None = None+ encoded_container: Any | None = None+ decode_thread: threading.Thread | None = None+ encode_thread: threading.Thread | None = None+ sessions: list[DirectDLSSGSession] = []+ transfer_pool: CudaTransferPool | None = None+ job: tempfile.TemporaryDirectory[str] | None = None+ stop, decode_stop = threading.Event(), threading.Event()+ failures: list[BaseException] = []+ timings: dict[str, float] = {+ "preflight_seconds": time.perf_counter() - operation_started,+ "runtime_prepare_seconds": runtime_prepare_seconds,+ "capability_probe_seconds": capability_probe_seconds,+ "session_initialization_seconds": 0.0,+ "probe_seconds": 0.0, "decode_seconds": 0.0, "software_prepare_seconds": 0.0,+ "bridge_input_seconds": 0.0, "optical_flow_seconds": 0.0,+ "dlssg_seconds": 0.0, "bridge_output_seconds": 0.0,+ "encode_seconds": 0.0, "cross_gpu_seconds": 0.0,+ }+ try:+ probe_start = time.perf_counter()+ metadata = ffmpeg.probe_video(+ source, count_mode="metadata", inspect_timestamps=True)+ source_rate = Fraction(metadata["rate"])+ cfr = bool(metadata.get("cfr", True))+ source_frames = int(metadata["frames"])+ if source_frames <= 0:+ source_frames = int(ffmpeg.probe_video(source, count_mode="exact")["frames"])+ duration = _duration_fraction(metadata, source_rate, source_frames, cfr=cfr)+ preview = options.preview_seconds is not None+ effective_hdr = bool(options.hdr_mode)+ if metadata["hdr"] and not effective_hdr:+ raise ValueError("HDR input requires Frame Interpolation HDR Mode with a 10-bit codec.")+ if preview:+ duration = min(duration, Fraction(str(options.preview_seconds)))+ source_frames = min(source_frames, ffmpeg.preview_frame_count(source, float(duration)))+ duration = min(duration, Fraction(source_frames, 1) / source_rate)+ plan = choose_interpolation_plan(+ source_rate, options.target_rate, options.engine,+ capabilities.native_multiplier, cfr=cfr)+ output_count = output_frame_count(duration, options.target_rate)+ timings["probe_seconds"] = time.perf_counter() - probe_start+ update(.01, "Preparing frame interpolation")++ selected_codec = options.codec+ video_gpu = ffmpeg.resolve_video_gpu(+ runtime.gpus, options.video_gpu_uuid, selected_codec,+ int(metadata["width"]), int(metadata["height"]))+ if _is_nvenc(selected_codec) and video_gpu is None:+ raise RuntimeError("The selected NVENC codec has no available encoding GPU.")+ ai_ordinal = int(ai_gpu["cuda_ordinal"])+ encode_ordinal = int(video_gpu["cuda_ordinal"]) if video_gpu is not None else ai_ordinal+ # The processing path is automatic, matching Upscale: an NVENC+ # output keeps decode/interpolation/encode on CUDA, while a CPU+ # codec uses the in-process host-staging ABI.+ want_cuda = automatic_cuda_path(selected_codec, metadata["rotation"])+ decode_device = HWAccel(+ "cuda", device=str(ai_ordinal), allow_software_fallback=True,+ options={"primary_ctx": "1"}, is_hw_owned=True) if want_cuda else None+ rotation_filter = {90: "transpose=clock", 180: "hflip,vflip", 270: "transpose=cclock"}.get(int(metadata["rotation"]), "")+ decoded_container = open_video_decoder(source, controller, pixel_format="p010le" if effective_hdr else "rgba", video_filter=rotation_filter)+ metadata["rotation"] = 0+ input_stream = decoded_container.streams.video[0]+ input_stream.thread_type = "AUTO"+ decoder = iter(decoded_container.decode(input_stream))+ tick = time.perf_counter()+ try:+ first_frame = _validate_decoded_frame(next(decoder))+ except StopIteration as exc:+ raise ValueError("The input contains no decodable video frames.") from exc+ timings["decode_seconds"] += time.perf_counter() - tick+ cuda_route = bool(want_cuda and first_frame.format.name == "cuda")+ decode_backend = "FFmpeg Vulkan/software fallback"+ output_p010 = bool(effective_hdr)+ encoder = _encoder(options, selected_codec, int(metadata["width"]),+ int(metadata["height"]), options.target_rate,+ effective_hdr, cuda_route, encode_ordinal)++ destination = prepare_output_dir(output_dir, default=OUTPUTS)+ stamp = time.strftime("%Y%m%d-%H%M%S") + f"-{time.time_ns()%1_000_000:06d}"+ extension = {"MP4": ".mp4", "MKV": ".mkv", "MOV": ".mov"}[options.container]+ output = unique_output_path(destination / output_filename(+ source, extension, options.rename_mode, options.custom_suffix,+ f"{source.stem}_{'DLSSFG_PREVIEW' if preview else 'DLSSFG'}_{stamp}"))+ output_file = OutputFile(output)+ JOBS.mkdir(exist_ok=True)+ job = tempfile.TemporaryDirectory(prefix="dlssg-bridge-", dir=JOBS)+ try:+ temp_video = Path(job.name) / ("encoded.mov" if options.container == "MOV" else+ "encoded.mkv" if options.container == "MKV" else "encoded.mp4")+ encoded_container = VideoOutput(temp_video, controller)+ encode_device = HWAccel(+ "cuda", device=str(encode_ordinal), options={"primary_ctx": "1"},+ is_hw_owned=True) if cuda_route else None+ output_stream = encoded_container.add_stream(+ encoder.name, rate=options.target_rate, hwaccel=encode_device)+ output_stream.width, output_stream.height = int(metadata["width"]), int(metadata["height"])+ output_stream.pix_fmt = encoder.pixel_format+ if cuda_route:+ output_stream.codec_context.sw_format = "p010le" if output_p010 else "nv12"+ output_tb = Fraction(1, 1) / options.target_rate+ output_stream.time_base = output_tb+ output_stream.codec_context.time_base = output_tb+ output_stream.codec_context.options = encoder.options+ output_stream.codec_context.bit_rate = encoder.bitrate+ if encoder.display == "prores_ks (Proxy)" and options.quality == "Auto (Default)":+ # Proxy's default quantizer remains visibly softer even with+ # the higher macroblock budget. Match its high-quality range.+ output_stream.codec_context.qscale = True+ output_stream.codec_context.global_quality = 3+ _set_color_properties(output_stream.codec_context, metadata, effective_hdr)+ if encoder.name == "ffv1":+ output_stream.codec_context.colorspace = 0 # RGB, no YUV matrix.+ output_stream.codec_context.color_range = 2 # Full range.+ output_stream.codec_context.open()++ generated_count = plan.generated_per_interval if plan.path == "Native DLSSG" else 1+ session_count = 1 if plan.path == "Native DLSSG" else plan.cascade_stages+ initialization_start = time.perf_counter()+ for _ in range(session_count):+ sessions.append(DirectDLSSGSession(+ int(metadata["width"]), int(metadata["height"]), generated_count,+ controller, ai_ordinal, hdr=effective_hdr))+ timings["session_initialization_seconds"] = time.perf_counter() - initialization_start+ colors = {"color_matrix": _matrix_code(metadata, hdr=effective_hdr),+ "color_range": _range_code(metadata),+ "color_primaries": _primaries_code(metadata),+ "color_transfer": _transfer_code(metadata),+ "rotation": int(metadata["rotation"])}+ stages = [DLSSGStage(+ session, generated_count, detect_source_cuts=index == 0,+ cuda_output=cuda_route, output_p010=output_p010, colors=colors,+ preserve_source_rgb=index == 0)+ for index, session in enumerate(sessions)]+ if cuda_route and encode_ordinal != ai_ordinal:+ transfer_pool = CudaTransferPool(ai_ordinal, encode_ordinal, controller)++ rgb_colorspace = {+ 0: Colorspace.ITU601, 1: Colorspace.ITU709,+ 2: Colorspace.BT2020, 3: Colorspace.FCC,+ 4: Colorspace.SMPTE240M,+ }[colors["color_matrix"]]++ decode_queue: queue.Queue = queue.Queue(maxsize=4)+ encode_queue: queue.Queue = queue.Queue(maxsize=4)++ def decode_worker() -> None:+ try:+ _put(decode_queue, first_frame, stop, controller, failures)+ while not stop.is_set() and not decode_stop.is_set():+ frame_start = time.perf_counter()+ try:+ frame = next(decoder)+ except StopIteration:+ timings["decode_seconds"] += time.perf_counter() - frame_start+ break+ timings["decode_seconds"] += time.perf_counter() - frame_start+ _validate_decoded_frame(frame)+ _put(decode_queue, frame, stop, controller, failures)+ except BaseException as exc:+ failures.append(exc); stop.set()+ finally:+ if not decode_stop.is_set() and not stop.is_set():+ with suppress(BaseException):+ _put(decode_queue, _END, stop, controller, failures)++ encoded_frames = [0]++ def encode_worker() -> None:+ try:+ while not stop.is_set():+ item = _get(encode_queue, stop, controller, failures)+ if item is _END:+ break+ frame, pts = item+ encode_start = time.perf_counter()+ frame.pts, frame.time_base, frame.duration = pts, output_tb, 1+ for packet in output_stream.encode(frame):+ encoded_container.mux(packet)+ timings["encode_seconds"] += time.perf_counter() - encode_start+ encoded_frames[0] += 1+ del frame, item+ if not failures and not controller.cancel.is_set():+ encode_start = time.perf_counter()+ for packet in output_stream.encode():+ encoded_container.mux(packet)+ timings["encode_seconds"] += time.perf_counter() - encode_start+ except BaseException as exc:+ failures.append(exc); stop.set()++ decode_thread = threading.Thread(target=decode_worker, name="dlssg-decoder", daemon=True)+ encode_thread = threading.Thread(target=encode_worker, name="dlssg-encoder", daemon=True)+ decode_thread.start(); encode_thread.start()+ pipeline_start = time.perf_counter()+ decoded = discontinuities = 0+ last_timestamp: Fraction | None = None+ origin_timestamp: Fraction | None = None+ source_segment = 0+ nominal = Fraction(1, 1) / source_rate+ source_dimensions = (int(first_frame.width), int(first_frame.height))++ def emit(selected: TimedFrame, index: int) -> None:+ frame = selected.encode_frame+ if isinstance(frame, DLSSGCudaSurface):+ convert_start = time.perf_counter()+ if encoder.name == "prores_ks" or not cuda_route:+ pixels = frame.to_host_rgb()+ if effective_hdr:+ # DLSSG returns normalized, transfer-encoded half float RGB.+ # Keep the 10-bit precision until the final 4:2:2 conversion.+ depth = 10+ maximum = (1 << depth) - 1+ rgb = np.rint(np.clip(pixels[..., :3].astype(np.float32),+ 0.0, 1.0) * maximum).astype(np.uint16)+ gbr = np.ascontiguousarray(rgb[..., [1, 2, 0]])+ frame = av.VideoFrame.from_ndarray(gbr, format=f"gbrp{depth}le")+ else:+ frame = av.VideoFrame.from_ndarray(pixels, format="rgba")+ else:+ yuv = frame.to_yuv_surface(+ color_matrix=colors["color_matrix"],+ color_range=colors["color_range"], p010=output_p010)+ frame = yuv.to_av_frame()+ timings["final_color_conversion_seconds"] = (+ timings.get("final_color_conversion_seconds", 0.0) ++ time.perf_counter() - convert_start)+ if transfer_pool is not None:+ transfer_start = time.perf_counter()+ frame, _detail = transfer_pool.transfer(frame)+ timings["cross_gpu_seconds"] += time.perf_counter() - transfer_start+ _put(encode_queue, (frame, index), stop, controller, failures)++ writer = NearestTimestampWriter(options.target_rate, output_count, emit)+ last_update = 0.0+ while decoded < source_frames:+ frame = _get(decode_queue, stop, controller, failures)+ if frame is _END:+ break+ if (int(frame.width), int(frame.height)) != source_dimensions:+ raise ValueError("Source dimensions changed during decoding.")+ raw_timestamp = (Fraction(frame.pts) * Fraction(frame.time_base)+ if frame.pts is not None and frame.time_base is not None+ else Fraction(decoded, 1) / source_rate)+ if origin_timestamp is None:+ origin_timestamp = raw_timestamp+ timestamp = raw_timestamp - origin_timestamp+ if last_timestamp is not None and (+ timestamp <= last_timestamp or timestamp - last_timestamp > nominal * 2):+ source_segment += 1+ discontinuities += 1+ last_timestamp = timestamp+ if cuda_route:+ bridge_frame, encode_frame = frame, frame+ else:+ prepare_start = time.perf_counter()+ if effective_hdr:+ bridge_frame = encode_frame = frame+ else:+ rgba = np.ascontiguousarray(frame.to_ndarray(format="rgba"))+ bridge_frame, encode_frame = rgba, frame+ timings["software_prepare_seconds"] += time.perf_counter() - prepare_start+ items = [TimedFrame(bridge_frame, encode_frame, timestamp, source_segment,+ "Source", decoded)]+ for stage in stages:+ next_items: list[TimedFrame] = []+ for item in items:+ native_start = time.perf_counter()+ produced = stage.push(item)+ native_elapsed = time.perf_counter() - native_start+ next_items.extend(produced)+ timings["bridge_total_seconds"] = timings.get("bridge_total_seconds", 0.0) + native_elapsed+ items = next_items+ for item in items:+ writer.push(item)+ decoded += 1+ del frame, items+ now = time.perf_counter()+ if now - last_update > .2:+ update(.04 + .82 * decoded / max(1, source_frames),+ f"Interpolating frames: {decoded:,} / {source_frames:,} frames")+ last_update = now+ if decoded != source_frames:+ raise RuntimeError(f"Decoded {decoded} source frames; expected {source_frames}.")+ writer.finish()+ _put(encode_queue, _END, threading.Event(), controller, failures)+ decode_stop.set()+ # A truncated preview intentionally stops before decoder EOF.+ # Free one or more queue slots so a producer already blocked in+ # _put can publish its current frame, observe decode_stop, and exit.+ while True:+ try:+ decode_queue.get_nowait()+ except queue.Empty:+ break+ decode_thread.join(timeout=30); encode_thread.join(timeout=300)+ if decode_thread.is_alive() or encode_thread.is_alive():+ raise RuntimeError("The bounded Frame Interpolation pipeline did not drain.")+ if failures:+ raise failures[0]+ if encoded_frames[0] != output_count:+ raise RuntimeError(f"Encoder accepted {encoded_frames[0]} frames; expected {output_count}.")+ timings["pipeline_seconds"] = time.perf_counter() - pipeline_start+ actual_encoder = encoded_container.actual_encoderencoded_container.close(); encoded_container = None- decoded_container.close(); decoded_container = None- gc.collect()-- session_diagnostics = [session.diagnostics() for session in sessions]- for session in sessions:- timings["bridge_input_seconds"] += session.stage_timings["input_ms"] / 1000- timings["optical_flow_seconds"] += session.stage_timings["optical_flow_ms"] / 1000- timings["dlssg_seconds"] += session.stage_timings["ngx_ms"] / 1000- timings["bridge_output_seconds"] += session.stage_timings["output_ms"] / 1000- session.close()- sessions.clear()- transfer_diagnostics = transfer_pool.diagnostics() if transfer_pool else {}- if transfer_pool:- transfer_pool.close(); transfer_pool = None- update(.9, "Muxing original audio, subtitles, chapters, and metadata")- mux_start = time.perf_counter()- audio_diagnostics: dict = {}- ffmpeg.final_mux(- temp_video, source, output_file.temporary, options.container, controller,- preserve_supported_subtitles=True,- source_time_origin=metadata.get("origin", 0),- audio_diagnostics=audio_diagnostics)- timings["mux_seconds"] = time.perf_counter() - mux_start- update(.96, "Verifying exact frame count, rational FPS, dimensions, and HDR")- verify_start = time.perf_counter()- verified = ffmpeg.probe_video(output_file.temporary, count_mode="packets", controller=controller)- if int(verified["frames"]) != output_count:- verified = ffmpeg.probe_video(output_file.temporary, count_mode="exact", controller=controller)- if int(verified["frames"]) != output_count or Fraction(verified["rate"]) != options.target_rate:- raise RuntimeError(- f"Output verification found {verified['frames']} frames at {verified['rate']} FPS; "- f"expected {output_count} at {options.target_rate}.")- if (int(verified["width"]), int(verified["height"])) != (- int(metadata["width"]), int(metadata["height"])):- raise RuntimeError("Output dimensions changed during interpolation.")- if effective_hdr and (not verified.get("hdr") or int(verified.get("depth", 0)) < 10):- raise RuntimeError("Saved interpolation failed HDR/10-bit verification.")- expected = {- "ProRes HQ": ("prores", "yuv422p10le", 10),- "FFV1 Lossless RGB 10-bit": ("ffv1", "gbrp10le", 10),- }.get(ffmpeg._normalize_codec(selected_codec))- if expected and (verified.get("codec"), verified.get("pixel_format"),- int(verified.get("depth") or 0)) != expected:- raise RuntimeError(f"Saved interpolation format does not match {selected_codec}.")- timings["verification_seconds"] = time.perf_counter() - verify_start- elapsed = time.perf_counter() - started- timings["total_seconds"] = elapsed- timings["steady_state_fps"] = output_count / max(timings["pipeline_seconds"], 1e-9)- stage_rates = [- output_count / max(timings["decode_seconds"], 1e-9),- output_count / max(timings.get("bridge_total_seconds", 0.0), 1e-9),- output_count / max(timings["encode_seconds"], 1e-9),- ]- timings["slowest_stage_ceiling_fps"] = min(stage_rates)- timings["ceiling_utilization"] = timings["steady_state_fps"] / max(min(stage_rates), 1e-9)- upload_bytes = sum(int(item.get("upload_bytes", 0)) for item in session_diagnostics)- download_bytes = sum(int(item.get("download_bytes", 0)) for item in session_diagnostics)- if transfer_diagnostics:- upload_bytes += int(transfer_diagnostics.get("pinned_upload_bytes", 0))- download_bytes += int(transfer_diagnostics.get("pinned_download_bytes", 0))- if cuda_route and encode_ordinal == ai_ordinal:- memory_path = "cuda_nvdec_shared_d3d12_dlssg_dlpack_nvenc"- if upload_bytes or download_bytes:- raise RuntimeError("Same-GPU CUDA route unexpectedly transferred full-frame host pixels.")- elif cuda_route:- memory_path = str(transfer_diagnostics.get("memory_path") or "cuda_cross_gpu")- else:- memory_path = "host_staging_inprocess_dlssg_encoder"- pool_pressure = {- "capacity": max((int(item.get("surface_pool_capacity", 0))- for item in session_diagnostics), default=0),- "allocated": max((int(item.get("surface_pool_allocated", 0))- for item in session_diagnostics), default=0),- "waits": sum(int(item.get("surface_pool_waits", 0))- for item in session_diagnostics),- }- scene_cuts = stages[0].scene_cuts if stages else 0- duplicate_intervals = sum(stage.duplicates for stage in stages)- # A target cadence such as 24 -> 60 does not necessarily land- # on every real source timestamp; those frames are scheduling- # alternatives, not decoder drops. Exact decoded/encoded counts- # have already been asserted above, so the pipeline dropped none.- unselected_source_frames = max(0, decoded - len(writer.selected_real_ids))- dropped = 0- diagnostics = {- "bridge": session_diagnostics, "cross_gpu_transfer": transfer_diagnostics,- "adapters": {"ai": ai_gpu, "decode": ai_gpu if cuda_route else "CPU",- "encode": video_gpu if _is_nvenc(selected_codec) else "CPU"},- "discontinuities": discontinuities, "duplicate_intervals": duplicate_intervals,- "unselected_source_frames": unselected_source_frames,- "audio_streams": audio_diagnostics.get("streams", []),- }- output_file.publish()- app_log.info("frame-interp", f"done src={source.name} out={output.name} "- f"frames={output_count} elapsed={elapsed:.2f}s memory={memory_path}")- update(1.0, "Frame interpolation complete — in-process GPU pipeline confirmed")- return FrameInterpolationResult(- output_path=str(output.resolve()), report_path=str(app_log.session_path()),- selected_path=plan.path, native_multiplier=plan.native_multiplier,- cascade_stages=plan.cascade_stages, copied_frames=writer.copied,- generated_frames=writer.generated, dropped_frames=dropped,- output_frames=output_count,- maximum_temporal_approximation_seconds=float(writer.max_error),- scene_cuts=scene_cuts, elapsed_seconds=elapsed, timings=timings,- bridge_version=capabilities.bridge_version,- bridge_abi_version=capabilities.bridge_abi_version,- nvof_available=capabilities.nvof_available, memory_path=memory_path,- decode_backend=decode_backend, encode_backend=encoder.display,- upload_bytes=upload_bytes, download_bytes=download_bytes,- surface_pool_pressure=pool_pressure, diagnostics=diagnostics)- finally:- # On a failure the output container may still own the temporary- # file. The outer handler closes it, then performs a second,- # reliable cleanup attempt without masking the original error.- with suppress(PermissionError):- job.cleanup()- except BaseException as exc:- stop.set(); decode_stop.set()- for thread in (decode_thread, encode_thread):- if thread is not None:- thread.join(timeout=2)- for session in sessions:- with suppress(Exception):- session.close(abort=True)- if transfer_pool is not None:- with suppress(Exception):- transfer_pool.close(abort=True)- if encoded_container is not None:- with suppress(Exception):- encoded_container.close()- if decoded_container is not None:- with suppress(Exception):- decoded_container.close()- if job is not None:- with suppress(Exception):- job.cleanup()- if output_file is not None:- output_file.cleanup(rollback=True)- if controller.cancel.is_set() or isinstance(exc, Cancelled):- raise Cancelled("Frame interpolation stopped by user.") from exc- failure_path = app_log.fail("frame-interp", f"DLSSFG_{source.stem}", exc)- raise RuntimeError(f"{exc}\nDetails: {failure_path.resolve()}") from exc- finally:- if output_file is not None:- output_file.cleanup()+ decoded_container.close(); decoded_container = None+ gc.collect()++ session_diagnostics = [session.diagnostics() for session in sessions]+ for session in sessions:+ timings["bridge_input_seconds"] += session.stage_timings["input_ms"] / 1000+ timings["optical_flow_seconds"] += session.stage_timings["optical_flow_ms"] / 1000+ timings["dlssg_seconds"] += session.stage_timings["ngx_ms"] / 1000+ timings["bridge_output_seconds"] += session.stage_timings["output_ms"] / 1000+ session.close()+ sessions.clear()+ transfer_diagnostics = transfer_pool.diagnostics() if transfer_pool else {}+ if transfer_pool:+ transfer_pool.close(); transfer_pool = None+ update(.9, "Muxing original audio, subtitles, chapters, and metadata")+ mux_start = time.perf_counter()+ audio_diagnostics: dict = {}+ ffmpeg.final_mux(+ temp_video, source, output_file.temporary, options.container, controller,+ preserve_supported_subtitles=True,+ source_time_origin=metadata.get("origin", 0),+ audio_diagnostics=audio_diagnostics)+ timings["mux_seconds"] = time.perf_counter() - mux_start+ update(.96, "Verifying exact frame count, rational FPS, dimensions, and HDR")+ verify_start = time.perf_counter()+ verified = ffmpeg.probe_video(output_file.temporary, count_mode="packets", controller=controller)+ if int(verified["frames"]) != output_count:+ verified = ffmpeg.probe_video(output_file.temporary, count_mode="exact", controller=controller)+ if int(verified["frames"]) != output_count or Fraction(verified["rate"]) != options.target_rate:+ raise RuntimeError(+ f"Output verification found {verified['frames']} frames at {verified['rate']} FPS; "+ f"expected {output_count} at {options.target_rate}.")+ if (int(verified["width"]), int(verified["height"])) != (+ int(metadata["width"]), int(metadata["height"])):+ raise RuntimeError("Output dimensions changed during interpolation.")+ if effective_hdr and (not verified.get("hdr") or int(verified.get("depth", 0)) < 10):+ raise RuntimeError("Saved interpolation failed HDR/10-bit verification.")+ expected = {+ "ProRes HQ": ("prores", "yuv422p10le", 10),+ "FFV1 Lossless RGB 10-bit": ("ffv1", "gbrp10le", 10),+ }.get(ffmpeg._normalize_codec(selected_codec))+ if expected and (verified.get("codec"), verified.get("pixel_format"),+ int(verified.get("depth") or 0)) != expected:+ raise RuntimeError(f"Saved interpolation format does not match {selected_codec}.")+ timings["verification_seconds"] = time.perf_counter() - verify_start+ elapsed = time.perf_counter() - started+ timings["total_seconds"] = elapsed+ timings["steady_state_fps"] = output_count / max(timings["pipeline_seconds"], 1e-9)+ stage_rates = [+ output_count / max(timings["decode_seconds"], 1e-9),+ output_count / max(timings.get("bridge_total_seconds", 0.0), 1e-9),+ output_count / max(timings["encode_seconds"], 1e-9),+ ]+ timings["slowest_stage_ceiling_fps"] = min(stage_rates)+ timings["ceiling_utilization"] = timings["steady_state_fps"] / max(min(stage_rates), 1e-9)+ upload_bytes = sum(int(item.get("upload_bytes", 0)) for item in session_diagnostics)+ download_bytes = sum(int(item.get("download_bytes", 0)) for item in session_diagnostics)+ if transfer_diagnostics:+ upload_bytes += int(transfer_diagnostics.get("pinned_upload_bytes", 0))+ download_bytes += int(transfer_diagnostics.get("pinned_download_bytes", 0))+ if cuda_route and encode_ordinal == ai_ordinal:+ memory_path = "cuda_nvdec_shared_d3d12_dlssg_dlpack_nvenc"+ if upload_bytes or download_bytes:+ raise RuntimeError("Same-GPU CUDA route unexpectedly transferred full-frame host pixels.")+ elif cuda_route:+ memory_path = str(transfer_diagnostics.get("memory_path") or "cuda_cross_gpu")+ else:+ memory_path = "host_staging_inprocess_dlssg_encoder"+ pool_pressure = {+ "capacity": max((int(item.get("surface_pool_capacity", 0))+ for item in session_diagnostics), default=0),+ "allocated": max((int(item.get("surface_pool_allocated", 0))+ for item in session_diagnostics), default=0),+ "waits": sum(int(item.get("surface_pool_waits", 0))+ for item in session_diagnostics),+ }+ scene_cuts = stages[0].scene_cuts if stages else 0+ duplicate_intervals = sum(stage.duplicates for stage in stages)+ # A target cadence such as 24 -> 60 does not necessarily land+ # on every real source timestamp; those frames are scheduling+ # alternatives, not decoder drops. Exact decoded/encoded counts+ # have already been asserted above, so the pipeline dropped none.+ unselected_source_frames = max(0, decoded - len(writer.selected_real_ids))+ dropped = 0+ diagnostics = {+ "bridge": session_diagnostics, "cross_gpu_transfer": transfer_diagnostics,+ "adapters": {"ai": ai_gpu, "decode": ai_gpu if cuda_route else "CPU",+ "encode": video_gpu if _is_nvenc(selected_codec) else "CPU"},+ "discontinuities": discontinuities, "duplicate_intervals": duplicate_intervals,+ "unselected_source_frames": unselected_source_frames,+ "audio_streams": audio_diagnostics.get("streams", []),+ }+ output_file.publish()+ app_log.info("frame-interp", f"done src={source.name} out={output.name} "+ f"frames={output_count} elapsed={elapsed:.2f}s memory={memory_path}")+ update(1.0, "Frame interpolation complete — in-process GPU pipeline confirmed")+ return FrameInterpolationResult(+ output_path=str(output.resolve()), report_path=str(app_log.session_path()),+ selected_path=plan.path, native_multiplier=plan.native_multiplier,+ cascade_stages=plan.cascade_stages, copied_frames=writer.copied,+ generated_frames=writer.generated, dropped_frames=dropped,+ output_frames=output_count,+ maximum_temporal_approximation_seconds=float(writer.max_error),+ scene_cuts=scene_cuts, elapsed_seconds=elapsed, timings=timings,+ bridge_version=capabilities.bridge_version,+ bridge_abi_version=capabilities.bridge_abi_version,+ nvof_available=capabilities.nvof_available, memory_path=memory_path,+ decode_backend=decode_backend, encode_backend=actual_encoder,+ upload_bytes=upload_bytes, download_bytes=download_bytes,+ surface_pool_pressure=pool_pressure, diagnostics=diagnostics)+ finally:+ # On a failure the output container may still own the temporary+ # file. The outer handler closes it, then performs a second,+ # reliable cleanup attempt without masking the original error.+ with suppress(PermissionError):+ job.cleanup()+ except BaseException as exc:+ stop.set(); decode_stop.set()+ for thread in (decode_thread, encode_thread):+ if thread is not None:+ thread.join(timeout=2)+ for session in sessions:+ with suppress(Exception):+ session.close(abort=True)+ if transfer_pool is not None:+ with suppress(Exception):+ transfer_pool.close(abort=True)+ if encoded_container is not None:+ with suppress(Exception):+ encoded_container.close()+ if decoded_container is not None:+ with suppress(Exception):+ decoded_container.close()+ if job is not None:+ with suppress(Exception):+ job.cleanup()+ if output_file is not None:+ output_file.cleanup(rollback=True)+ if controller.cancel.is_set() or isinstance(exc, Cancelled):+ raise Cancelled("Frame interpolation stopped by user.") from exc+ failure_path = app_log.fail("frame-interp", f"DLSSFG_{source.stem}", exc)+ raise RuntimeError(f"{exc}\nDetails: {failure_path.resolve()}") from exc+ finally:+ if output_file is not None:+ output_file.cleanup()diff --git a/src/live/mpv_embed.py b/src/live/mpv_embed.pyindex 4bb2f22..bf61d07 100644--- a/src/live/mpv_embed.py+++ b/src/live/mpv_embed.py@@ -39,10 +39,6 @@ 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()diff --git a/src/live/pipeline.py b/src/live/pipeline.pyindex cb892e2..25f2351 100644--- a/src/live/pipeline.py+++ b/src/live/pipeline.py@@ -1,963 +1,965 @@-from __future__ import annotations--import atexit-import json-import math-import os-import queue-import re-import shutil-import subprocess-import threading-import time-from contextlib import suppress-from dataclasses import replace-from fractions import Fraction-from pathlib import Path--import av-import numpy as np-from av.codec.hwaccel import HWAccel--from ..core.gpu_selection import resolve_runtime_ai_gpu-from ..core.jobs import BoundedLogBuffer, Cancelled, JobController, active_job, drain_bounded_text-from ..core import app_log-from ..core.ffmpeg import chroma_location_code, decoded_rgba+from __future__ import annotations++import atexit+import json+import math+import os+import queue+import re+import shutil+import subprocess+import threading+import time+from contextlib import suppress+from dataclasses import replace+from fractions import Fraction+from pathlib import Path++import av+import numpy as np+from av.codec.hwaccel import HWAccel++from ..core.gpu_selection import resolve_runtime_ai_gpu+from ..core.jobs import BoundedLogBuffer, Cancelled, JobController, active_job, drain_bounded_text+from ..core import app_log+from ..core.ffmpeg import chroma_location_code, decoded_rgbafrom ..core.paths import FFMPEG, LIVE_DIRfrom ..core.runtime import (DLSSFrameSession, prepare_runtime, resolve_native_settings,resolve_output_size, resolve_upscaling_mode, resize_fit,- rotate_frame, verify_feature_18)-from ..settings.storage import processing_gpu_settings-from ..neural_rendering.video.guides import TemporalGuideGenerator-from .effects import EffectSettings, EffectUpdates, NativeDeadline, EFFECT_REPLACEMENT_TIMEOUT-from .hls_server import HlsServer-from .models import (LIVE_FPS_CHOICES,- LIVE_MAX_HEIGHTS, LIVE_SOURCE_QUALITY_CHOICES, LiveOptions, LiveSessionInfo, ResolvedSource)-from .player import check_live_binaries, launch_mpv, mpv_tail-from .source_resolver import _classify, input_args, probe_source, resolve_source, run_capture-from .transport import TIME_BASE, AdaptiveRate, PipeReader, TimestampMuxer, VideoFrame, get, put--_LOCK = threading.Lock()-_CURRENT: LiveSession | None = None-_LAST: LiveSessionInfo | None = None---def _fit_height(width: int, height: int, max_height: int) -> tuple[int, int]:- scale = min(1.0, max_height / height)- return max(2, round(width * scale / 2) * 2), max(2, round(height * scale / 2) * 2)---def validate_options(options: LiveOptions) -> None:- if not options.source.strip():- raise ValueError("Enter a video file or a stream URL.")- if options.max_height not in LIVE_MAX_HEIGHTS:- raise ValueError(f"Max input height must be one of: {', '.join(map(str, LIVE_MAX_HEIGHTS))}.")- if options.source_quality not in LIVE_SOURCE_QUALITY_CHOICES:- raise ValueError("Choose a valid Source quality.")- if options.target_fps not in LIVE_FPS_CHOICES:- raise ValueError("Choose a valid frame rate.")- if options.segment_seconds not in (1, 2, 4, 6):- raise ValueError("Segment length must be 1, 2, 4 or 6 seconds.")- if not math.isfinite(options.buffer_seconds) or not 2 <= options.buffer_seconds <= 30:- raise ValueError("Playback buffer must be between 2 and 30 seconds.")- if not 1 <= options.queue_frames <= 8 or not 5 <= options.network_timeout <= 60:- raise ValueError("Invalid Live queue size or network timeout.")- resolve_upscaling_mode(options.upscaling_factor)- resolve_native_settings(options)---def _redact(text: str) -> str:- # Keep diagnostic errors, never store signed CDN query tokens.- return re.sub(r"(https?://[^\s?]+)\?[^\s'\"]+", r"\1?<redacted>", text)---class LiveSession(threading.Thread):- """Bounded decode/scene reset -> feature 18 -> encode -> buffered playback."""-- def __init__(self, options: LiveOptions) -> None:- super().__init__(daemon=True, name="dlss5-live-session")- self.options = replace(options)- self.effects = EffectUpdates(options)- self.controller = JobController()- self.info = LiveSessionInfo(running=True, processing=True, status="Starting...")- self._info_lock = threading.Lock()- self._ready = threading.Event()- self._produced = threading.Event()- self._mpv: subprocess.Popen | None = None- self._session_dir: Path | None = None- self._player_attempted = False- self._player_state: dict = {}- self._playback_started: float | None = None- self._last_ui = 0.0- self._last_progress = time.monotonic()- self._error: str | None = None- self._error_lock = threading.Lock()- self._logs: dict[str, BoundedLogBuffer] = {}- self._log_threads: list[threading.Thread] = []- self._rate: AdaptiveRate | None = None- self._bridge_logs: list[str] = []- self._feature_evidence: dict = {}- self._bridge_status: dict = {}- self._title = ""- self._published_seconds = 0.0- self._published_sequence = -1- self._segment_count = 0- self._first_frame_at: float | None = None- self._finished = False- self._started_at = time.monotonic()-- def _set(self, **fields) -> None:- with self._info_lock:- for key, value in fields.items():- setattr(self.info, key, value)-- def snapshot(self) -> LiveSessionInfo:- effects = self.effects.snapshot()- with self._info_lock:- return replace(self.info, failures=list(self.info.failures), **effects)-- def request_effects(self, settings) -> bool:- return self.effects.submit(settings)-- def stop(self) -> None:- self.effects.finish()- if self.info.processing:- self._set(status="Stopping...")- self.controller.stop()-+ rotate_frame, verify_feature_18)+from ..settings.storage import processing_gpu_settings+from ..neural_rendering.video.guides import TemporalGuideGenerator+from .effects import EffectSettings, EffectUpdates, NativeDeadline, EFFECT_REPLACEMENT_TIMEOUT+from .hls_server import HlsServer+from .models import (LIVE_FPS_CHOICES,+ LIVE_MAX_HEIGHTS, LIVE_SOURCE_QUALITY_CHOICES, LiveOptions, LiveSessionInfo, ResolvedSource)+from .player import check_live_binaries, launch_mpv, mpv_tail+from .source_resolver import _classify, input_args, probe_source, resolve_source, run_capture+from .transport import TIME_BASE, AdaptiveRate, PipeReader, TimestampMuxer, VideoFrame, get, put++_LOCK = threading.Lock()+_CURRENT: LiveSession | None = None+_LAST: LiveSessionInfo | None = None+++def _fit_height(width: int, height: int, max_height: int) -> tuple[int, int]:+ scale = min(1.0, max_height / height)+ return max(2, round(width * scale / 2) * 2), max(2, round(height * scale / 2) * 2)+++def validate_options(options: LiveOptions) -> None:+ if not options.source.strip():+ raise ValueError("Enter a video file or a stream URL.")+ if options.max_height not in LIVE_MAX_HEIGHTS:+ raise ValueError(f"Max input height must be one of: {', '.join(map(str, LIVE_MAX_HEIGHTS))}.")+ if options.source_quality not in LIVE_SOURCE_QUALITY_CHOICES:+ raise ValueError("Choose a valid Source quality.")+ if options.target_fps not in LIVE_FPS_CHOICES:+ raise ValueError("Choose a valid frame rate.")+ if options.segment_seconds not in (1, 2, 4, 6):+ raise ValueError("Segment length must be 1, 2, 4 or 6 seconds.")+ if not math.isfinite(options.buffer_seconds) or not 2 <= options.buffer_seconds <= 30:+ raise ValueError("Playback buffer must be between 2 and 30 seconds.")+ if not 1 <= options.queue_frames <= 8 or not 5 <= options.network_timeout <= 60:+ raise ValueError("Invalid Live queue size or network timeout.")+ resolve_upscaling_mode(options.upscaling_factor)+ resolve_native_settings(options)+++def _redact(text: str) -> str:+ # Keep diagnostic errors, never store signed CDN query tokens.+ return re.sub(r"(https?://[^\s?]+)\?[^\s'\"]+", r"\1?<redacted>", text)+++class LiveSession(threading.Thread):+ """Bounded decode/scene reset -> feature 18 -> encode -> buffered playback."""++ def __init__(self, options: LiveOptions) -> None:+ super().__init__(daemon=True, name="dlss5-live-session")+ self.options = replace(options)+ self.effects = EffectUpdates(options)+ self.controller = JobController()+ self.info = LiveSessionInfo(running=True, processing=True, status="Starting...")+ self._info_lock = threading.Lock()+ self._ready = threading.Event()+ self._produced = threading.Event()+ self._mpv: subprocess.Popen | None = None+ self._session_dir: Path | None = None+ self._player_attempted = False+ self._player_state: dict = {}+ self._playback_started: float | None = None+ self._last_ui = 0.0+ self._last_progress = time.monotonic()+ self._error: str | None = None+ self._error_lock = threading.Lock()+ self._logs: dict[str, BoundedLogBuffer] = {}+ self._log_threads: list[threading.Thread] = []+ self._rate: AdaptiveRate | None = None+ self._bridge_logs: list[str] = []+ self._feature_evidence: dict = {}+ self._bridge_status: dict = {}+ self._title = ""+ self._published_seconds = 0.0+ self._published_sequence = -1+ self._segment_count = 0+ self._first_frame_at: float | None = None+ self._finished = False+ self._started_at = time.monotonic()++ def _set(self, **fields) -> None:+ with self._info_lock:+ for key, value in fields.items():+ setattr(self.info, key, value)++ def snapshot(self) -> LiveSessionInfo:+ effects = self.effects.snapshot()+ with self._info_lock:+ return replace(self.info, failures=list(self.info.failures), **effects)++ def request_effects(self, settings) -> bool:+ return self.effects.submit(settings)++ def stop(self) -> None:+ self.effects.finish()+ if self.info.processing:+ self._set(status="Stopping...")+ self.controller.stop()+def _stage_error(self, stage: str, exc: Exception) -> None:with self._error_lock:if self._error is None and not self.controller.cancel.is_set():self._error = _redact(f"{stage}: {exc}")app_log.error("live", f"{stage}: {exc}")- self.controller.stop()-- def _spawn(self, name: str, command: list[str], **kwargs) -> subprocess.Popen:- process = subprocess.Popen(command, stderr=subprocess.PIPE,- creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0), **kwargs)- self.controller.register(process)- log = self._logs[name] = BoundedLogBuffer(max_tail=80)- thread = threading.Thread(target=drain_bounded_text, args=(process.stderr, log), daemon=True)- thread.start()- self._log_threads.append(thread)- return process-+ self.controller.stop()++ def _spawn(self, name: str, command: list[str], **kwargs) -> subprocess.Popen:+ from ..core.ffmpeg.vulkan import prepare_command+ command = prepare_command(command, dimensions=tuple(map(int, self.snapshot().output_size.split("x"))) if name == "encoder" else None)+ process = subprocess.Popen(command, stderr=subprocess.PIPE,+ creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0), **kwargs)+ self.controller.register(process)+ log = self._logs[name] = BoundedLogBuffer(max_tail=80)+ thread = threading.Thread(target=drain_bounded_text, args=(process.stderr, log), daemon=True)+ thread.start()+ self._log_threads.append(thread)+ return process+def _process_error(self, name: str, process: subprocess.Popen) -> RuntimeError:detail = "\n".join(self._logs[name].snapshot()[-12:])app_log.error("live-ffmpeg", f"{name} exited code={process.returncode}", detail)- return RuntimeError(_redact(f"{name} exited with code {process.returncode}.\n{detail}"))-- def _remember_native(self, native) -> None:- self._bridge_logs = [*self._bridge_logs, *native.bridge_logs][-500:]- self._bridge_status = native.structured_status()-- def _verified_effect_session(self, settings: EffectSettings, native_args: dict,- item: VideoFrame, index: int):- native = None- try:+ return RuntimeError(_redact(f"{name} exited with code {process.returncode}.\n{detail}"))++ def _remember_native(self, native) -> None:+ self._bridge_logs = [*self._bridge_logs, *native.bridge_logs][-500:]+ self._bridge_status = native.structured_status()++ def _verified_effect_session(self, settings: EffectSettings, native_args: dict,+ item: VideoFrame, index: int):+ native = None+ try:with NativeDeadline(self.controller, EFFECT_REPLACEMENT_TIMEOUT) as deadline:- # The replacement session keeps the current frame boundary.- native = DLSSFrameSession(**native_args, controller=deadline,- native_settings=resolve_native_settings(settings),- composition_mask=settings.nr_mask)- native.diagnostics.encode_backend = (- "nvenc" if self.info.encoder == "NVIDIA NVENC" else "cpu"- )- start = time.perf_counter()- output, pts = native.process(index=index, rgba=item.rgba,- reset=True, pts=item.pts)- cost = time.perf_counter() - start- if pts != item.pts:- raise RuntimeError("Replacement bridge session returned a different frame timestamp.")- evidence = verify_feature_18(native.bridge_logs, native.structured_status())- self._feature_evidence = dict(evidence)- return native, output, cost- except Exception:- if native is not None:- self._remember_native(native)- native.abort()- raise-- def _replace_effects(self, native, request, native_args: dict, item: VideoFrame, index: int):- start = time.perf_counter()- self._remember_native(native)- native.abort() # release resources/config/log ownership before starting another- error = ""- try:- replacement, output, cost = self._verified_effect_session(request.settings, native_args, item, index)- except Cancelled:- raise- except Exception as exc:- if self.controller.cancel.is_set():- raise Cancelled("Live stopped.") from exc- error = _redact(str(exc))- try:- replacement, output, cost = self._verified_effect_session(self.effects.applied, native_args, item, index)- except Cancelled:- raise- except Exception as recovery:- detail = f"{error}; recovery failed: {_redact(str(recovery))}"- self.effects.complete(request, pts=item.pts, milliseconds=(time.perf_counter()-start)*1000,- error=detail, restored=False)- raise RuntimeError(detail) from recovery- self.effects.complete(request, pts=item.pts, milliseconds=(time.perf_counter()-start)*1000,- error=error)- self._rate.reset_measurements()- self._last_progress = time.monotonic()- self._write_report()- return replacement, output, cost-- def _select_encoder(self, gpus: tuple, selected_uuid: str, width: int, height: int) -> tuple[bool, int | None]:- candidates = [g for g in gpus if g.get("cuda_ordinal") is not None- and (selected_uuid == "auto" or g.get("uuid") == selected_uuid)]- for gpu in candidates:- ordinal = int(gpu["cuda_ordinal"])- try:- result = run_capture([str(FFMPEG), "-v", "error", "-f", "lavfi", "-i",- f"color=size={width}x{height}:rate=1", "-frames:v", "1", "-c:v", "h264_nvenc",- "-gpu", str(ordinal), "-f", "null", "-"], self.controller, 15)- if result.returncode == 0:- return True, ordinal- except Cancelled:- raise- except RuntimeError:- continue- # Live has always allowed a CPU fallback. Probe it via the real encoder- # startup, and include its cost in automatic cadence selection.- return False, None-+ # The replacement session keeps the current frame boundary.+ native = DLSSFrameSession(**native_args, controller=deadline,+ native_settings=resolve_native_settings(settings),+ composition_mask=settings.nr_mask)+ native.diagnostics.encode_backend = (+ "nvenc" if self.info.encoder == "NVIDIA NVENC" else "cpu"+ )+ start = time.perf_counter()+ output, pts = native.process(index=index, rgba=item.rgba,+ reset=True, pts=item.pts)+ cost = time.perf_counter() - start+ if pts != item.pts:+ raise RuntimeError("Replacement bridge session returned a different frame timestamp.")+ evidence = verify_feature_18(native.bridge_logs, native.structured_status())+ self._feature_evidence = dict(evidence)+ return native, output, cost+ except Exception:+ if native is not None:+ self._remember_native(native)+ native.abort()+ raise++ def _replace_effects(self, native, request, native_args: dict, item: VideoFrame, index: int):+ start = time.perf_counter()+ self._remember_native(native)+ native.abort() # release resources/config/log ownership before starting another+ error = ""+ try:+ replacement, output, cost = self._verified_effect_session(request.settings, native_args, item, index)+ except Cancelled:+ raise+ except Exception as exc:+ if self.controller.cancel.is_set():+ raise Cancelled("Live stopped.") from exc+ error = _redact(str(exc))+ try:+ replacement, output, cost = self._verified_effect_session(self.effects.applied, native_args, item, index)+ except Cancelled:+ raise+ except Exception as recovery:+ detail = f"{error}; recovery failed: {_redact(str(recovery))}"+ self.effects.complete(request, pts=item.pts, milliseconds=(time.perf_counter()-start)*1000,+ error=detail, restored=False)+ raise RuntimeError(detail) from recovery+ self.effects.complete(request, pts=item.pts, milliseconds=(time.perf_counter()-start)*1000,+ error=error)+ self._rate.reset_measurements()+ self._last_progress = time.monotonic()+ self._write_report()+ return replacement, output, cost++ def _select_encoder(self, gpus: tuple, selected_uuid: str, width: int, height: int) -> tuple[bool, int | None]:+ candidates = [g for g in gpus if g.get("cuda_ordinal") is not None+ and (selected_uuid == "auto" or g.get("uuid") == selected_uuid)]+ for gpu in candidates:+ ordinal = int(gpu["cuda_ordinal"])+ try:+ result = run_capture([str(FFMPEG), "-v", "error", "-f", "lavfi", "-i",+ f"color=size={width}x{height}:rate=1", "-frames:v", "1", "-c:v", "h264_nvenc",+ "-gpu", str(ordinal), "-f", "null", "-"], self.controller, 15)+ if result.returncode == 0:+ return True, ordinal+ except Cancelled:+ raise+ except RuntimeError:+ continue+ # Live has always allowed a CPU fallback. Probe it via the real encoder+ # startup, and include its cost in automatic cadence selection.+ return False, None+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- # FFmpeg repair those jumps for both streams before preserving the- # resulting timeline through DLSS. copyts disables that repair.- command += (["-dts_delta_threshold", "2"] if source.is_live- else ["-copyts", "-start_at_zero"])- command += [*input_args(source.video_url, source.video_headers, opts.network_timeout),- "-thread_queue_size", "32", "-i", source.video_url]- audio_input = "0"- if source.audio_url and source.audio_url != source.video_url:- command += [*input_args(source.audio_url, source.audio_headers, opts.network_timeout),- "-thread_queue_size", "32", "-i", source.audio_url]- audio_input = "1"+ opts = self.options+ command = [str(FFMPEG), "-hide_banner", "-loglevel", "warning", "-nostdin", "-filter_threads", "2"]+ # HLS broadcasts can jump clocks at reconnects/ad boundaries. Let+ # FFmpeg repair those jumps for both streams before preserving the+ # resulting timeline through DLSS. copyts disables that repair.+ command += (["-dts_delta_threshold", "2"] if source.is_live+ else ["-copyts", "-start_at_zero"])+ command += [*input_args(source.video_url, source.video_headers, opts.network_timeout),+ "-thread_queue_size", "32", "-i", source.video_url]+ audio_input = "0"+ if source.audio_url and source.audio_url != source.video_url:+ command += [*input_args(source.audio_url, source.audio_headers, opts.network_timeout),+ "-thread_queue_size", "32", "-i", source.audio_url]+ audio_input = "1"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",- "-c:v", "copy",- "-c:a", "pcm_s16le", "-ar", "48000", "-ac", "2",- "-af", "aresample=async=1:first_pts=0",- "-f", "nut", "-write_index", "0", "pipe:1"]- return command- # Software decoding and CPU encoding retain a host frame boundary;- # Neural Rendering still evaluates those frames through CUDA/D3D12.- filters = [] if opts.target_fps == "Source" else [f"fps={rate}"]- filters += [f"scale={width}:{height}:flags=lanczos", "setsar=1"]- command += ["-map", "0:v:0", "-map", f"{audio_input}:a:0?", "-sn", "-dn",- "-vf", ",".join(filters),- "-c:v", "rawvideo", "-pix_fmt",- "rgba64le" if self._source_depth > 8 else "rgba", "-threads:v", "1",- "-c:a", "pcm_s16le", "-ar", "48000", "-ac", "2",- "-af", "aresample=async=1:first_pts=0",- "-fps_mode", "passthrough", "-f", "nut", "-write_index", "0", "pipe:1"]- return command-- def _encoder_command(self, rate, gpu: int | None, nvenc: bool) -> list[str]:- opts = self.options- if nvenc:- video = ["-c:v", "h264_nvenc"]- if gpu is not None:- video += ["-gpu", str(gpu)]- video += ["-preset", "p1", "-tune", "ll", "-rc", "vbr", "-cq", "23", "-b:v", "0",- "-rc-lookahead", "0", "-zerolatency", "1", "-bf", "0", "-forced-idr", "1"]- else:- video = ["-c:v", "libx264", "-preset", "ultrafast", "-tune", "zerolatency", "-crf", "23",- "-sc_threshold", "0"]- # Timestamps from NUT survive frame selection. There is no -r or CFR- # conversion after DLSS to squeeze skipped source time out of the video.- return [str(FFMPEG), "-hide_banner", "-loglevel", "warning", "-nostdin", "-y",- "-filter_threads", "2", "-probesize", "32768", "-analyzeduration", "0",- "-f", "nut", "-i", "pipe:0", "-map", "0:v:0", "-map", "0:a:0?",- *video, "-pix_fmt", "yuv420p", "-fps_mode", "passthrough", "-enc_time_base", "1:90000",- "-g", str(max(1, math.ceil(float(rate) * opts.segment_seconds))),- "-force_key_frames", f"expr:gte(t,n_forced*{opts.segment_seconds})",- "-c:a", "aac", "-b:a", "160k", "-max_interleave_delta", "1000000",- "-f", "hls", "-hls_time", str(opts.segment_seconds),- "-hls_list_size", str(max(12, math.ceil((opts.buffer_seconds + 60) / opts.segment_seconds))),- "-hls_delete_threshold", "6", "-hls_flags", "delete_segments+independent_segments+temp_file",- "-hls_segment_filename", "seg%07d.ts", "index.m3u8"]-- def _decode(self, decoder: subprocess.Popen, prepared: queue.Queue, width: int, height: int) -> None:- assert self._rate is not None- rate = self._rate- try:- with av.open(PipeReader(decoder.stdout), format="nut", options={"probesize": "32768", "analyzeduration": "0"}) as container:- audio = next(iter(container.streams.audio), None)- put(prepared, audio, self.controller.cancel) # stream header (None means silent)- guides = TemporalGuideGenerator(width, height, flow_width=320)- index = 0- last_pts: int | None = None- sampled = 0- for packet in container.demux():- if self.controller.cancel.is_set():- raise Cancelled("Live stopped.")- if not packet.size:- continue- self._last_progress = time.monotonic()- if packet.stream.type == "audio":- put(prepared, packet, self.controller.cancel)- continue- if packet.stream.type != "video":- continue- pts = round(packet.pts * packet.time_base / TIME_BASE)- current = index- index += 1- self._set(source_frames=index)- if not rate.accepts(current):- sampled += 1- self._set(sampled_frames=sampled)- continue- high_depth = self._source_depth > 8- if packet.size != width * height * 4 * (2 if high_depth else 1):- raise RuntimeError("Decoder returned an incomplete RGBA frame.")- rgba = np.frombuffer(packet, np.uint16 if high_depth else np.uint8).reshape(height, width, 4)- start = time.perf_counter()- guide = guides.process(rgba)- guide_ms = (time.perf_counter() - start) * 1000- old = self.snapshot().guide_ms- self._set(guide_ms=guide_ms if not old else old * 0.9 + guide_ms * 0.1)- # Temporal history spans the selected cadence, but a real- # timestamp discontinuity must reset both guide and DLSS.- discontinuity = last_pts is not None and (pts <= last_pts or (pts - last_pts) * TIME_BASE > 0.5)- if discontinuity:- guides.previous_gray = None- duration = (max(1, round(packet.duration * packet.time_base / TIME_BASE))- if self.options.target_fps == "Source" and packet.duration- else max(1, round(1 / rate.fps / TIME_BASE)))- put(prepared, VideoFrame(- current, pts, duration, rgba, reset=guide.reset or discontinuity- ), self.controller.cancel)- last_pts = pts- code = decoder.wait(timeout=5)- if code:- raise self._process_error("decoder", decoder)- if not index:- raise RuntimeError("The decoder produced no video frames.")- put(prepared, None, self.controller.cancel)- except Cancelled:- pass- except Exception as exc:- self._stage_error("Decode / scene analysis", exc)-- def _encode(self, encoder: subprocess.Popen, outgoing: queue.Queue, width: int, height: int) -> None:- muxer = None- try:- audio = get(outgoing, self.controller.cancel)- muxer = TimestampMuxer(- encoder.stdin, width, height, self._rate.rate, audio,- pix_fmt="rgba64le" if self._source_depth > 8 else "rgba",- )- while True:- item = get(outgoing, self.controller.cancel)- if item is None:- break- start = time.perf_counter()- muxer.write(item)- if isinstance(item, VideoFrame):- cost = (time.perf_counter() - start) * 1000- old = self.snapshot().encode_ms- self._set(encode_ms=cost if not old else old * 0.9 + cost * 0.1,- media_seconds=float((item.pts + item.duration) * TIME_BASE))- self._last_progress = time.monotonic()- muxer.close()- muxer = None- encoder.stdin.close()- code = encoder.wait(timeout=30)- if code:- raise self._process_error("encoder", encoder)- except Cancelled:- pass- except Exception as exc:- if encoder.poll() is not None and not self.controller.cancel.is_set():- exc = self._process_error("encoder", encoder)- self._stage_error("Encode / audio mux", exc)- finally:- if muxer:- try:- muxer.close()- except Exception:- pass-- def _produce_cuda(- self, resolved: ResolvedSource, metadata: dict, in_w: int, in_h: int,- out_w: int, out_h: int, factor: float, mode: dict, prepared_runtime,- gpu: dict, ordinal: int,- ) -> None:- """Compressed demux -> PyAV NVDEC -> feature 18 -> PyAV NVENC -> HLS."""- if self._session_dir is None or self._rate is None:- raise RuntimeError("Live session storage and cadence must be initialized.")- decoder = native = input_container = hls = None- watchdog_done = threading.Event()- watchdog = threading.Thread(target=self._watchdog, args=(watchdog_done,), daemon=True)- self._last_progress = time.monotonic()- watchdog.start()- matrix_name = str(metadata.get("color_space") or "").casefold()- color_matrix = 2 if "2020" in matrix_name else (- 0 if matrix_name in {"bt470bg", "smpte170m", "smpte240m", "fcc"} else 1- )- color_range = int(- str(metadata.get("color_range") or "").casefold() in {"pc", "jpeg", "full"}- )- try:- decoder = self._spawn(- "demux", self._decoder_command(resolved, in_w, in_h, self._rate.rate, cuda=True),- stdout=subprocess.PIPE, stdin=subprocess.DEVNULL,- )- decode_device = HWAccel(- "cuda", device=str(ordinal), allow_software_fallback=True,- options={"primary_ctx": "1"}, is_hw_owned=True,- )- input_container = av.open(- PipeReader(decoder.stdout), mode="r", format="nut",- options={"probesize": "32768", "analyzeduration": "0"},- hwaccel=decode_device,- )- video_input = input_container.streams.video[0]- audio_input = next(iter(input_container.streams.audio), None)-- encode_device = HWAccel(- "cuda", device=str(ordinal), options={"primary_ctx": "1"}, is_hw_owned=True- )- list_size = max(- 12, math.ceil((self.options.buffer_seconds + 60) / self.options.segment_seconds)- )- hls = av.open(- str(self._session_dir / "index.m3u8"), mode="w", format="hls",- options={- "hls_time": str(self.options.segment_seconds),- "hls_list_size": str(list_size),- "hls_delete_threshold": "6",- "hls_flags": "delete_segments+independent_segments+temp_file",- "hls_segment_filename": str(self._session_dir / "seg%07d.ts"),- },- )- video_output = hls.add_stream(- "h264_nvenc", rate=self._rate.rate, hwaccel=encode_device- )- video_output.width, video_output.height = out_w, out_h- video_output.pix_fmt = "cuda"- video_output.codec_context.sw_format = "nv12"- video_output.time_base = TIME_BASE- video_output.codec_context.time_base = TIME_BASE- video_output.codec_context.gop_size = max(- 1, math.ceil(float(self._rate.rate) * self.options.segment_seconds)- )- video_output.codec_context.max_b_frames = 0- video_output.codec_context.options = {- "preset": "p1", "tune": "ll", "rc": "vbr", "cq": "23",- "gpu": str(ordinal), "rc-lookahead": "0", "zerolatency": "1",- "forced-idr": "1",- }- audio_output = audio_resampler = None- if audio_input is not None:- audio_output = hls.add_stream("aac", rate=48000)- audio_output.codec_context.layout = "stereo"- audio_output.codec_context.bit_rate = 160_000- audio_output.time_base = Fraction(1, 48000)- audio_output.codec_context.time_base = Fraction(1, 48000)- audio_resampler = av.AudioResampler(format="fltp", layout="stereo", rate=48000)-- 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, cuda_video=True,- )- native = DLSSFrameSession(- **native_args, native_settings=resolve_native_settings(self.options),- composition_mask=self.options.nr_mask,- controller=self.controller,- )- native.diagnostics.source_format = str(metadata["pixel_format"])- self._ready.set()- processing_start = time.perf_counter()- pacing_seconds = 0.0- processed = source_frames = sampled = 0- last_pts: int | None = None- software_guides = TemporalGuideGenerator(out_w, out_h, flow_width=320)-- for packet in input_container.demux():- if self.controller.cancel.is_set():- raise Cancelled("Live stopped.")- self._last_progress = time.monotonic()- if packet.stream.type == "audio":- if audio_output is not None and audio_resampler is not None:- for audio_frame in packet.decode():- for converted in audio_resampler.resample(audio_frame):- for encoded_packet in audio_output.encode(converted):- hls.mux(encoded_packet)- continue- if packet.stream.type != "video":- continue- for frame in packet.decode():- current = source_frames- source_frames += 1- self._set(source_frames=source_frames)- if not self._rate.accepts(current):- sampled += 1- self._set(sampled_frames=sampled)- continue- frame_time_base = frame.time_base or video_input.time_base- source_pts = int(frame.pts if frame.pts is not None else current)- pts = round(source_pts * frame_time_base / TIME_BASE)- discontinuity = last_pts is not None and (- pts <= last_pts or (pts - last_pts) * TIME_BASE > 0.5- )- duration = (- max(1, round(frame.duration * frame_time_base / TIME_BASE))- if self.options.target_fps == "Source" and frame.duration- else max(1, round(1 / self._rate.fps / TIME_BASE))- )- self._update_playback()- pacing_seconds += self._pace(pts)- guide_started = time.perf_counter()- rgba = None- if frame.format.name == "cuda":- scene_score, reset = native.score_cuda_frame(- frame, color_matrix=color_matrix, color_range=color_range- )- else:- rgba = rotate_frame(- decoded_rgba(frame, metadata["depth"]), int(metadata.get("rotation") or 0)- )- if rgba.shape[:2] != (out_h, out_w):- rgba = resize_fit(rgba, out_w, out_h)- rgba = np.ascontiguousarray(rgba)- guide = software_guides.process(rgba)- scene_score, reset = guide.scene_score, guide.reset- guide_cost = time.perf_counter() - guide_started- reset = bool(reset or discontinuity)-- def evaluate(settings, force_reset: bool):- resolved_settings = resolve_native_settings(settings)- if (- settings.nr_mask != native.composition_mask- or int(resolved_settings["mask_feather"])- != int(native.native_settings.get("mask_feather", 0))- ):- native.update_composition_mask(- settings.nr_mask, int(resolved_settings["mask_feather"])- )- native.native_settings = resolved_settings- native.bridge_status["nr_passes"] = int(resolved_settings["nr_passes"])- native.bridge_status["allocated_feature_instances"] = int(- resolved_settings["nr_passes"]- )- native.bridge_status["composition"]["color_strength"] = float(- resolved_settings["color_strength"]- )- native.bridge_status["composition"]["tone_preservation"] = float(- resolved_settings["tone_preservation"]- )- native.bridge_status["composition"]["face_skin_protection"] = float(- resolved_settings["face_skin_protection"]- )- native.bridge_status["composition"]["grain_preservation"] = float(- resolved_settings["grain_preservation"]- )- native.bridge_status["temporal_stabilization"]["shimmer_suppression"] = float(- resolved_settings["shimmer_suppression"]- )- evaluation_started = time.perf_counter()- values = dict(- index=processed, reset=force_reset, scene_score=scene_score,- pts=pts, duration=duration, time_base=TIME_BASE,- color_matrix=color_matrix, color_range=color_range,- chroma_location=chroma_location_code(metadata),- )- if frame.format.name == "cuda":- result, result_pts = native.process_video_frame(- frame=frame, rotation=int(metadata.get("rotation") or 0), **values- )- else:- result, result_pts = native.process_video_frame(rgba=rgba, **values)- return result, result_pts, time.perf_counter() - evaluation_started-- request = self.effects.take_due()- if request is None:- output, output_pts, cost = evaluate(self.effects.applied, reset)- else:+ # 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",+ "-c:v", "copy",+ "-c:a", "pcm_s16le", "-ar", "48000", "-ac", "2",+ "-af", "aresample=async=1:first_pts=0",+ "-f", "nut", "-write_index", "0", "pipe:1"]+ return command+ # Software decoding and CPU encoding retain a host frame boundary;+ # Neural Rendering still evaluates those frames through CUDA/D3D12.+ filters = [] if opts.target_fps == "Source" else [f"fps={rate}"]+ filters += [f"scale={width}:{height}:flags=lanczos", "setsar=1"]+ command += ["-map", "0:v:0", "-map", f"{audio_input}:a:0?", "-sn", "-dn",+ "-vf", ",".join(filters),+ "-c:v", "rawvideo", "-pix_fmt",+ "rgba64le" if self._source_depth > 8 else "rgba", "-threads:v", "1",+ "-c:a", "pcm_s16le", "-ar", "48000", "-ac", "2",+ "-af", "aresample=async=1:first_pts=0",+ "-fps_mode", "passthrough", "-f", "nut", "-write_index", "0", "pipe:1"]+ return command++ def _encoder_command(self, rate, gpu: int | None, nvenc: bool) -> list[str]:+ opts = self.options+ if nvenc:+ video = ["-c:v", "h264_nvenc"]+ if gpu is not None:+ video += ["-gpu", str(gpu)]+ video += ["-preset", "p1", "-tune", "ll", "-rc", "vbr", "-cq", "23", "-b:v", "0",+ "-rc-lookahead", "0", "-zerolatency", "1", "-bf", "0", "-forced-idr", "1"]+ else:+ video = ["-c:v", "libx264", "-preset", "ultrafast", "-tune", "zerolatency", "-crf", "23",+ "-sc_threshold", "0"]+ # Timestamps from NUT survive frame selection. There is no -r or CFR+ # conversion after DLSS to squeeze skipped source time out of the video.+ return [str(FFMPEG), "-hide_banner", "-loglevel", "warning", "-nostdin", "-y",+ "-filter_threads", "2", "-probesize", "32768", "-analyzeduration", "0",+ "-f", "nut", "-i", "pipe:0", "-map", "0:v:0", "-map", "0:a:0?",+ *video, "-pix_fmt", "yuv420p", "-fps_mode", "passthrough", "-enc_time_base", "1:90000",+ "-g", str(max(1, math.ceil(float(rate) * opts.segment_seconds))),+ "-force_key_frames", f"expr:gte(t,n_forced*{opts.segment_seconds})",+ "-c:a", "aac", "-b:a", "160k", "-max_interleave_delta", "1000000",+ "-f", "hls", "-hls_time", str(opts.segment_seconds),+ "-hls_list_size", str(max(12, math.ceil((opts.buffer_seconds + 60) / opts.segment_seconds))),+ "-hls_delete_threshold", "6", "-hls_flags", "delete_segments+independent_segments+temp_file",+ "-hls_segment_filename", "seg%07d.ts", "index.m3u8"]++ def _decode(self, decoder: subprocess.Popen, prepared: queue.Queue, width: int, height: int) -> None:+ assert self._rate is not None+ rate = self._rate+ try:+ with av.open(PipeReader(decoder.stdout), format="nut", options={"probesize": "32768", "analyzeduration": "0"}) as container:+ audio = next(iter(container.streams.audio), None)+ put(prepared, audio, self.controller.cancel) # stream header (None means silent)+ guides = TemporalGuideGenerator(width, height, flow_width=320)+ index = 0+ last_pts: int | None = None+ sampled = 0+ for packet in container.demux():+ if self.controller.cancel.is_set():+ raise Cancelled("Live stopped.")+ if not packet.size:+ continue+ self._last_progress = time.monotonic()+ if packet.stream.type == "audio":+ put(prepared, packet, self.controller.cancel)+ continue+ if packet.stream.type != "video":+ continue+ pts = round(packet.pts * packet.time_base / TIME_BASE)+ current = index+ index += 1+ self._set(source_frames=index)+ if not rate.accepts(current):+ sampled += 1+ self._set(sampled_frames=sampled)+ continue+ high_depth = self._source_depth > 8+ if packet.size != width * height * 4 * (2 if high_depth else 1):+ raise RuntimeError("Decoder returned an incomplete RGBA frame.")+ rgba = np.frombuffer(packet, np.uint16 if high_depth else np.uint8).reshape(height, width, 4)+ start = time.perf_counter()+ guide = guides.process(rgba)+ guide_ms = (time.perf_counter() - start) * 1000+ old = self.snapshot().guide_ms+ self._set(guide_ms=guide_ms if not old else old * 0.9 + guide_ms * 0.1)+ # Temporal history spans the selected cadence, but a real+ # timestamp discontinuity must reset both guide and DLSS.+ discontinuity = last_pts is not None and (pts <= last_pts or (pts - last_pts) * TIME_BASE > 0.5)+ if discontinuity:+ guides.previous_gray = None+ duration = (max(1, round(packet.duration * packet.time_base / TIME_BASE))+ if self.options.target_fps == "Source" and packet.duration+ else max(1, round(1 / rate.fps / TIME_BASE)))+ put(prepared, VideoFrame(+ current, pts, duration, rgba, reset=guide.reset or discontinuity+ ), self.controller.cancel)+ last_pts = pts+ code = decoder.wait(timeout=5)+ if code:+ raise self._process_error("decoder", decoder)+ if not index:+ raise RuntimeError("The decoder produced no video frames.")+ put(prepared, None, self.controller.cancel)+ except Cancelled:+ pass+ except Exception as exc:+ self._stage_error("Decode / scene analysis", exc)++ def _encode(self, encoder: subprocess.Popen, outgoing: queue.Queue, width: int, height: int) -> None:+ muxer = None+ try:+ audio = get(outgoing, self.controller.cancel)+ muxer = TimestampMuxer(+ encoder.stdin, width, height, self._rate.rate, audio,+ pix_fmt="rgba64le" if self._source_depth > 8 else "rgba",+ )+ while True:+ item = get(outgoing, self.controller.cancel)+ if item is None:+ break+ start = time.perf_counter()+ muxer.write(item)+ if isinstance(item, VideoFrame):+ cost = (time.perf_counter() - start) * 1000+ old = self.snapshot().encode_ms+ self._set(encode_ms=cost if not old else old * 0.9 + cost * 0.1,+ media_seconds=float((item.pts + item.duration) * TIME_BASE))+ self._last_progress = time.monotonic()+ muxer.close()+ muxer = None+ encoder.stdin.close()+ code = encoder.wait(timeout=30)+ if code:+ raise self._process_error("encoder", encoder)+ except Cancelled:+ pass+ except Exception as exc:+ if encoder.poll() is not None and not self.controller.cancel.is_set():+ exc = self._process_error("encoder", encoder)+ self._stage_error("Encode / audio mux", exc)+ finally:+ if muxer:+ try:+ muxer.close()+ except Exception:+ pass++ def _produce_cuda(+ self, resolved: ResolvedSource, metadata: dict, in_w: int, in_h: int,+ out_w: int, out_h: int, factor: float, mode: dict, prepared_runtime,+ gpu: dict, ordinal: int,+ ) -> None:+ """Compressed demux -> PyAV NVDEC -> feature 18 -> PyAV NVENC -> HLS."""+ if self._session_dir is None or self._rate is None:+ raise RuntimeError("Live session storage and cadence must be initialized.")+ decoder = native = input_container = hls = None+ watchdog_done = threading.Event()+ watchdog = threading.Thread(target=self._watchdog, args=(watchdog_done,), daemon=True)+ self._last_progress = time.monotonic()+ watchdog.start()+ matrix_name = str(metadata.get("color_space") or "").casefold()+ color_matrix = 2 if "2020" in matrix_name else (+ 0 if matrix_name in {"bt470bg", "smpte170m", "smpte240m", "fcc"} else 1+ )+ color_range = int(+ str(metadata.get("color_range") or "").casefold() in {"pc", "jpeg", "full"}+ )+ try:+ decoder = self._spawn(+ "demux", self._decoder_command(resolved, in_w, in_h, self._rate.rate, cuda=True),+ stdout=subprocess.PIPE, stdin=subprocess.DEVNULL,+ )+ decode_device = HWAccel(+ "cuda", device=str(ordinal), allow_software_fallback=True,+ options={"primary_ctx": "1"}, is_hw_owned=True,+ )+ input_container = av.open(+ PipeReader(decoder.stdout), mode="r", format="nut",+ options={"probesize": "32768", "analyzeduration": "0"},+ hwaccel=decode_device,+ )+ video_input = input_container.streams.video[0]+ audio_input = next(iter(input_container.streams.audio), None)++ encode_device = HWAccel(+ "cuda", device=str(ordinal), options={"primary_ctx": "1"}, is_hw_owned=True+ )+ list_size = max(+ 12, math.ceil((self.options.buffer_seconds + 60) / self.options.segment_seconds)+ )+ hls = av.open(+ str(self._session_dir / "index.m3u8"), mode="w", format="hls",+ options={+ "hls_time": str(self.options.segment_seconds),+ "hls_list_size": str(list_size),+ "hls_delete_threshold": "6",+ "hls_flags": "delete_segments+independent_segments+temp_file",+ "hls_segment_filename": str(self._session_dir / "seg%07d.ts"),+ },+ )+ video_output = hls.add_stream(+ "h264_nvenc", rate=self._rate.rate, hwaccel=encode_device+ )+ video_output.width, video_output.height = out_w, out_h+ video_output.pix_fmt = "cuda"+ video_output.codec_context.sw_format = "nv12"+ video_output.time_base = TIME_BASE+ video_output.codec_context.time_base = TIME_BASE+ video_output.codec_context.gop_size = max(+ 1, math.ceil(float(self._rate.rate) * self.options.segment_seconds)+ )+ video_output.codec_context.max_b_frames = 0+ video_output.codec_context.options = {+ "preset": "p1", "tune": "ll", "rc": "vbr", "cq": "23",+ "gpu": str(ordinal), "rc-lookahead": "0", "zerolatency": "1",+ "forced-idr": "1",+ }+ audio_output = audio_resampler = None+ if audio_input is not None:+ audio_output = hls.add_stream("aac", rate=48000)+ audio_output.codec_context.layout = "stereo"+ audio_output.codec_context.bit_rate = 160_000+ audio_output.time_base = Fraction(1, 48000)+ audio_output.codec_context.time_base = Fraction(1, 48000)+ audio_resampler = av.AudioResampler(format="fltp", layout="stereo", rate=48000)++ 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, cuda_video=True,+ )+ native = DLSSFrameSession(+ **native_args, native_settings=resolve_native_settings(self.options),+ composition_mask=self.options.nr_mask,+ controller=self.controller,+ )+ native.diagnostics.source_format = str(metadata["pixel_format"])+ self._ready.set()+ processing_start = time.perf_counter()+ pacing_seconds = 0.0+ processed = source_frames = sampled = 0+ last_pts: int | None = None+ software_guides = TemporalGuideGenerator(out_w, out_h, flow_width=320)++ for packet in input_container.demux():+ if self.controller.cancel.is_set():+ raise Cancelled("Live stopped.")+ self._last_progress = time.monotonic()+ if packet.stream.type == "audio":+ if audio_output is not None and audio_resampler is not None:+ for audio_frame in packet.decode():+ for converted in audio_resampler.resample(audio_frame):+ for encoded_packet in audio_output.encode(converted):+ hls.mux(encoded_packet)+ continue+ if packet.stream.type != "video":+ continue+ for frame in packet.decode():+ current = source_frames+ source_frames += 1+ self._set(source_frames=source_frames)+ if not self._rate.accepts(current):+ sampled += 1+ self._set(sampled_frames=sampled)+ continue+ frame_time_base = frame.time_base or video_input.time_base+ source_pts = int(frame.pts if frame.pts is not None else current)+ pts = round(source_pts * frame_time_base / TIME_BASE)+ discontinuity = last_pts is not None and (+ pts <= last_pts or (pts - last_pts) * TIME_BASE > 0.5+ )+ duration = (+ max(1, round(frame.duration * frame_time_base / TIME_BASE))+ if self.options.target_fps == "Source" and frame.duration+ else max(1, round(1 / self._rate.fps / TIME_BASE))+ )+ self._update_playback()+ pacing_seconds += self._pace(pts)+ guide_started = time.perf_counter()+ rgba = None+ if frame.format.name == "cuda":+ scene_score, reset = native.score_cuda_frame(+ frame, color_matrix=color_matrix, color_range=color_range+ )+ else:+ rgba = rotate_frame(+ decoded_rgba(frame, metadata["depth"]), int(metadata.get("rotation") or 0)+ )+ if rgba.shape[:2] != (out_h, out_w):+ rgba = resize_fit(rgba, out_w, out_h)+ rgba = np.ascontiguousarray(rgba)+ guide = software_guides.process(rgba)+ scene_score, reset = guide.scene_score, guide.reset+ guide_cost = time.perf_counter() - guide_started+ reset = bool(reset or discontinuity)++ def evaluate(settings, force_reset: bool):+ resolved_settings = resolve_native_settings(settings)+ if (+ settings.nr_mask != native.composition_mask+ or int(resolved_settings["mask_feather"])+ != int(native.native_settings.get("mask_feather", 0))+ ):+ native.update_composition_mask(+ settings.nr_mask, int(resolved_settings["mask_feather"])+ )+ native.native_settings = resolved_settings+ native.bridge_status["nr_passes"] = int(resolved_settings["nr_passes"])+ native.bridge_status["allocated_feature_instances"] = int(+ resolved_settings["nr_passes"]+ )+ native.bridge_status["composition"]["color_strength"] = float(+ resolved_settings["color_strength"]+ )+ native.bridge_status["composition"]["tone_preservation"] = float(+ resolved_settings["tone_preservation"]+ )+ native.bridge_status["composition"]["face_skin_protection"] = float(+ resolved_settings["face_skin_protection"]+ )+ native.bridge_status["composition"]["grain_preservation"] = float(+ resolved_settings["grain_preservation"]+ )+ native.bridge_status["temporal_stabilization"]["shimmer_suppression"] = float(+ resolved_settings["shimmer_suppression"]+ )+ evaluation_started = time.perf_counter()+ values = dict(+ index=processed, reset=force_reset, scene_score=scene_score,+ pts=pts, duration=duration, time_base=TIME_BASE,+ color_matrix=color_matrix, color_range=color_range,+ chroma_location=chroma_location_code(metadata),+ )+ if frame.format.name == "cuda":+ result, result_pts = native.process_video_frame(+ frame=frame, rotation=int(metadata.get("rotation") or 0), **values+ )+ else:+ result, result_pts = native.process_video_frame(rgba=rgba, **values)+ return result, result_pts, time.perf_counter() - evaluation_started++ request = self.effects.take_due()+ if request is None:+ output, output_pts, cost = evaluate(self.effects.applied, reset)+ else:old_settings = self.effects.appliedupdate_started = time.perf_counter()try:- output, output_pts, cost = evaluate(request.settings, True)- self.effects.complete(- request, pts=pts,- milliseconds=(time.perf_counter() - update_started) * 1000,- )- except Cancelled:- raise- except Exception as exc:- output, output_pts, cost = evaluate(old_settings, True)- self.effects.complete(- request, pts=pts,- milliseconds=(time.perf_counter() - update_started) * 1000,- error=_redact(str(exc)),- )- self._rate.reset_measurements()- self._write_report()- if output_pts != pts:- raise RuntimeError("Neural Rendering changed a Live frame timestamp.")- encode_started = time.perf_counter()- for encoded_packet in video_output.encode(output):- hls.mux(encoded_packet)- encode_cost = time.perf_counter() - encode_started- processed += 1- last_pts = pts- if processed == 1:- self._feature_evidence = verify_feature_18(- native.bridge_logs, native.structured_status()- )- self._first_frame_at = time.monotonic()- old_info = self.snapshot()- self._rate.observe(cost, guide_cost, encode_cost)- guide_ms, encode_ms = guide_cost * 1000, encode_cost * 1000- self._set(- processed_frames=processed,- guide_ms=guide_ms if not old_info.guide_ms else old_info.guide_ms * 0.9 + guide_ms * 0.1,- dlss_ms=cost * 1000 if processed == 1 else old_info.dlss_ms * 0.9 + cost * 100,- encode_ms=encode_ms if not old_info.encode_ms else old_info.encode_ms * 0.9 + encode_ms * 0.1,- target_fps=self._rate.fps,- effective_fps=processed / max(- time.perf_counter() - processing_start - pacing_seconds, 0.001- ),- media_seconds=float((pts + duration) * TIME_BASE),- )- self._last_progress = time.monotonic()-- for encoded_packet in video_output.encode():- hls.mux(encoded_packet)- if audio_output is not None:- if audio_resampler is not None:- for converted in audio_resampler.resample(None):- for encoded_packet in audio_output.encode(converted):- hls.mux(encoded_packet)- for encoded_packet in audio_output.encode():- hls.mux(encoded_packet)- hls.close()- hls = None- input_container.close()- input_container = None- code = decoder.wait(timeout=10)- if code:- raise self._process_error("demux", decoder)- if not processed:- raise RuntimeError("The decoder produced no accepted video frames.")- native.close()- self._remember_native(native)- self._bridge_status = native.structured_status()- native = None- self.effects.finish()- self._finished = True- finally:- watchdog_done.set()- if native is not None:- self._remember_native(native)- self._bridge_status = native.structured_status()- with suppress(Exception):- native.abort()- if hls is not None:- with suppress(Exception):- hls.close()- if input_container is not None:- with suppress(Exception):- input_container.close()- if decoder is not None:- if decoder.poll() is None:- decoder.terminate()- with suppress(subprocess.TimeoutExpired):- decoder.wait(timeout=5)- if decoder.poll() is None:- decoder.kill()- decoder.wait(timeout=5)- self.controller.unregister(decoder)- watchdog.join(timeout=1)-- def _playlist(self) -> tuple[int, float]:- try:- lines = (self._session_dir / "index.m3u8").read_text(encoding="utf-8").splitlines()- except OSError:- return 0, 0.0- sequence = 0- duration = 0.0- count = 0- for line in lines:- if line.startswith("#EXT-X-MEDIA-SEQUENCE:"):- sequence = int(line.split(":")[1])- elif line.startswith("#EXTINF:"):- duration = float(line.split(":")[1].split(",")[0])- elif line and not line.startswith("#"):- if sequence > self._published_sequence:- self._published_seconds += duration- self._published_sequence = sequence- self._segment_count += 1- count += 1- sequence += 1- return count, self._published_seconds-- def _update_playback(self, *, finished: bool = False) -> None:- now = time.monotonic()- if now - self._last_ui < 0.25 and not finished:- return- self._last_ui = now- count, published = self._playlist()- if self._mpv:- try:- self._player_state = json.loads((self._session_dir / "player.json").read_text(encoding="utf-8"))- except (OSError, ValueError):- pass+ output, output_pts, cost = evaluate(request.settings, True)+ self.effects.complete(+ request, pts=pts,+ milliseconds=(time.perf_counter() - update_started) * 1000,+ )+ except Cancelled:+ raise+ except Exception as exc:+ output, output_pts, cost = evaluate(old_settings, True)+ self.effects.complete(+ request, pts=pts,+ milliseconds=(time.perf_counter() - update_started) * 1000,+ error=_redact(str(exc)),+ )+ self._rate.reset_measurements()+ self._write_report()+ if output_pts != pts:+ raise RuntimeError("Neural Rendering changed a Live frame timestamp.")+ encode_started = time.perf_counter()+ for encoded_packet in video_output.encode(output):+ hls.mux(encoded_packet)+ encode_cost = time.perf_counter() - encode_started+ processed += 1+ last_pts = pts+ if processed == 1:+ self._feature_evidence = verify_feature_18(+ native.bridge_logs, native.structured_status()+ )+ self._first_frame_at = time.monotonic()+ old_info = self.snapshot()+ self._rate.observe(cost, guide_cost, encode_cost)+ guide_ms, encode_ms = guide_cost * 1000, encode_cost * 1000+ self._set(+ processed_frames=processed,+ guide_ms=guide_ms if not old_info.guide_ms else old_info.guide_ms * 0.9 + guide_ms * 0.1,+ dlss_ms=cost * 1000 if processed == 1 else old_info.dlss_ms * 0.9 + cost * 100,+ encode_ms=encode_ms if not old_info.encode_ms else old_info.encode_ms * 0.9 + encode_ms * 0.1,+ target_fps=self._rate.fps,+ effective_fps=processed / max(+ time.perf_counter() - processing_start - pacing_seconds, 0.001+ ),+ media_seconds=float((pts + duration) * TIME_BASE),+ )+ self._last_progress = time.monotonic()++ for encoded_packet in video_output.encode():+ hls.mux(encoded_packet)+ if audio_output is not None:+ if audio_resampler is not None:+ for converted in audio_resampler.resample(None):+ for encoded_packet in audio_output.encode(converted):+ hls.mux(encoded_packet)+ for encoded_packet in audio_output.encode():+ hls.mux(encoded_packet)+ hls.close()+ hls = None+ input_container.close()+ input_container = None+ code = decoder.wait(timeout=10)+ if code:+ raise self._process_error("demux", decoder)+ if not processed:+ raise RuntimeError("The decoder produced no accepted video frames.")+ native.close()+ self._remember_native(native)+ self._bridge_status = native.structured_status()+ native = None+ self.effects.finish()+ self._finished = True+ finally:+ watchdog_done.set()+ if native is not None:+ self._remember_native(native)+ self._bridge_status = native.structured_status()+ with suppress(Exception):+ native.abort()+ if hls is not None:+ with suppress(Exception):+ hls.close()+ if input_container is not None:+ with suppress(Exception):+ input_container.close()+ if decoder is not None:+ if decoder.poll() is None:+ decoder.terminate()+ with suppress(subprocess.TimeoutExpired):+ decoder.wait(timeout=5)+ if decoder.poll() is None:+ decoder.kill()+ decoder.wait(timeout=5)+ self.controller.unregister(decoder)+ watchdog.join(timeout=1)++ def _playlist(self) -> tuple[int, float]:+ try:+ lines = (self._session_dir / "index.m3u8").read_text(encoding="utf-8").splitlines()+ except OSError:+ return 0, 0.0+ sequence = 0+ duration = 0.0+ count = 0+ for line in lines:+ if line.startswith("#EXT-X-MEDIA-SEQUENCE:"):+ sequence = int(line.split(":")[1])+ elif line.startswith("#EXTINF:"):+ duration = float(line.split(":")[1].split(",")[0])+ elif line and not line.startswith("#"):+ if sequence > self._published_sequence:+ self._published_seconds += duration+ self._published_sequence = sequence+ self._segment_count += 1+ count += 1+ sequence += 1+ return count, self._published_seconds++ def _update_playback(self, *, finished: bool = False) -> None:+ now = time.monotonic()+ if now - self._last_ui < 0.25 and not finished:+ return+ self._last_ui = now+ count, published = self._playlist()+ if self._mpv:+ try:+ self._player_state = json.loads((self._session_dir / "player.json").read_text(encoding="utf-8"))+ except (OSError, ValueError):+ passcode = 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)+ av_sync_ms=float(self._player_state.get("avsync", 0)) * 1000)if code is not None and not finished:if code:tail = mpv_tail(self._mpv)app_log.error("live-mpv", f"MPV exited code={code}", tail)raise RuntimeError(f"MPV exited with code {code}.")self.stop()- return- ready = count and (published >= self.options.buffer_seconds or finished)- if ready and not self._player_attempted:- self._player_attempted = True- self._playback_started = now+ return+ ready = count and (published >= self.options.buffer_seconds or finished)+ if ready and not self._player_attempted:+ self._player_attempted = True+ self._playback_started = nowif 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- else max(0, now - self._playback_started) if self._playback_started else 0)- buffer = max(0, published - position)- status = (f"Playing: {self._title}" if self._player_attempted else f"Buffering: {self._title}")- if finished:- status = f"Finished processing: {self._title}. Playback available until Stop."- status += (f"\n{info.target_fps:.2f} fps target | {info.effective_fps:.1f} fps processing | "- f"{info.processed_frames} enhanced | {info.sampled_frames} sampled out | {buffer:.1f}s buffered")- self._set(status=status, segments=self._segment_count, buffer_seconds=buffer,- elapsed_seconds=now - self._started_at)-- def _pace(self, pts: int) -> float:- # Compress time only in the processing schedule, never in media PTS.- # Keep finite videos from racing through/deleting their HLS window.- start = time.perf_counter()- while self._playback_started is not None and not self.controller.cancel.is_set():- position = (float(self._player_state.get("position", 0)) if self._mpv- else time.monotonic() - self._playback_started)- if pts * TIME_BASE - position <= self.options.buffer_seconds + 2 * self.options.segment_seconds:- break- self._update_playback()- self.controller.cancel.wait(0.05)- return time.perf_counter() - start-- def _watchdog(self, done: threading.Event) -> None:- while not done.wait(0.5):- if self.controller.cancel.is_set():- return- if self._playback_started and (self._player_state.get("paused") or self._player_state.get("buffering")):- # Pausing the player intentionally backpressures the pipeline.- # Only explicit pause excuses inactivity; rebuffering doesn't.- if self._player_state.get("paused"):- self._last_progress = time.monotonic()- if time.monotonic() - self._last_progress > max(45, self.options.network_timeout * 2):- self._stage_error("Live stalled", RuntimeError("No pipeline progress. Check the source/network and try again."))- return-- def _produce(self) -> None:- options = self.options- self._set(status="Resolving source...")- resolved = resolve_source(options.source, options.max_height, self.controller,- source_quality=options.source_quality)- self._title = resolved.title- self._set(status=f"Probing {resolved.title}...")- metadata = probe_source(resolved, self.controller, options.network_timeout)- self._source_depth = int(metadata["depth"])- source_size = f"{metadata['width']}x{metadata['height']}"- source_limit = options.max_height if options.source_quality == "Auto" else int(options.source_quality)- source_note = (f"Requested up to {source_limit}p; received {source_size}."- if resolved.kind in ("youtube", "twitch") else- "Source quality selection applies to YouTube/Twitch pages; using the supplied source.")- if resolved.kind in ("youtube", "twitch") and metadata["height"] != source_limit:- source_note += " The resolved stream differs from the requested height."- self._set(source_size=source_size, source_quality=options.source_quality, source_quality_note=source_note)- self._rate = AdaptiveRate(metadata["rate"], options.target_fps)- self._set(source_fps=float(metadata["rate"]), target_fps=self._rate.fps)- in_w, in_h = _fit_height(metadata["width"], metadata["height"], options.max_height)- factor, mode = resolve_upscaling_mode(options.upscaling_factor)- 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()+ self._set(mpv_running=True)+ info = self.snapshot()+ position = (float(self._player_state.get("position", 0)) if self._mpv+ else max(0, now - self._playback_started) if self._playback_started else 0)+ buffer = max(0, published - position)+ status = (f"Playing: {self._title}" if self._player_attempted else f"Buffering: {self._title}")+ if finished:+ status = f"Finished processing: {self._title}. Playback available until Stop."+ status += (f"\n{info.target_fps:.2f} fps target | {info.effective_fps:.1f} fps processing | "+ f"{info.processed_frames} enhanced | {info.sampled_frames} sampled out | {buffer:.1f}s buffered")+ self._set(status=status, segments=self._segment_count, buffer_seconds=buffer,+ elapsed_seconds=now - self._started_at)++ def _pace(self, pts: int) -> float:+ # Compress time only in the processing schedule, never in media PTS.+ # Keep finite videos from racing through/deleting their HLS window.+ start = time.perf_counter()+ while self._playback_started is not None and not self.controller.cancel.is_set():+ position = (float(self._player_state.get("position", 0)) if self._mpv+ else time.monotonic() - self._playback_started)+ if pts * TIME_BASE - position <= self.options.buffer_seconds + 2 * self.options.segment_seconds:+ break+ self._update_playback()+ self.controller.cancel.wait(0.05)+ return time.perf_counter() - start++ def _watchdog(self, done: threading.Event) -> None:+ while not done.wait(0.5):+ if self.controller.cancel.is_set():+ return+ if self._playback_started and (self._player_state.get("paused") or self._player_state.get("buffering")):+ # Pausing the player intentionally backpressures the pipeline.+ # Only explicit pause excuses inactivity; rebuffering doesn't.+ if self._player_state.get("paused"):+ self._last_progress = time.monotonic()+ if time.monotonic() - self._last_progress > max(45, self.options.network_timeout * 2):+ self._stage_error("Live stalled", RuntimeError("No pipeline progress. Check the source/network and try again."))+ return++ def _produce(self) -> None:+ options = self.options+ self._set(status="Resolving source...")+ resolved = resolve_source(options.source, options.max_height, self.controller,+ source_quality=options.source_quality)+ self._title = resolved.title+ self._set(status=f"Probing {resolved.title}...")+ metadata = probe_source(resolved, self.controller, options.network_timeout)+ self._source_depth = int(metadata["depth"])+ source_size = f"{metadata['width']}x{metadata['height']}"+ source_limit = options.max_height if options.source_quality == "Auto" else int(options.source_quality)+ source_note = (f"Requested up to {source_limit}p; received {source_size}."+ if resolved.kind in ("youtube", "twitch") else+ "Source quality selection applies to YouTube/Twitch pages; using the supplied source.")+ if resolved.kind in ("youtube", "twitch") and metadata["height"] != source_limit:+ source_note += " The resolved stream differs from the requested height."+ self._set(source_size=source_size, source_quality=options.source_quality, source_quality_note=source_note)+ self._rate = AdaptiveRate(metadata["rate"], options.target_fps)+ self._set(source_fps=float(metadata["rate"]), target_fps=self._rate.fps)+ in_w, in_h = _fit_height(metadata["width"], metadata["height"], options.max_height)+ factor, mode = resolve_upscaling_mode(options.upscaling_factor)+ 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)- # NVENC on the AI GPU keeps frames on device; a CPU encoder uses- # host frame boundaries around the same CUDA/D3D12 evaluation.- nvenc, ordinal = self._select_encoder(prepared_runtime.gpus, ai_uuid, out_w, out_h)+ # NVENC on the AI GPU keeps frames on device; a CPU encoder uses+ # host frame boundaries around the same CUDA/D3D12 evaluation.+ nvenc, ordinal = False, Noneself._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")+ encoder="FFmpeg/Vulkan (software fallback)")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,- )- return- native = None- processes: list[subprocess.Popen] = []- threads: list[threading.Thread] = []- watchdog_done = threading.Event()- self._last_progress = time.monotonic()- watchdog = threading.Thread(target=self._watchdog, args=(watchdog_done,), daemon=True)- watchdog.start()- try:- 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),- composition_mask=options.nr_mask,- controller=self.controller)- native.diagnostics.encode_backend = "nvenc" if nvenc else "cpu"- native.diagnostics.source_format = str(metadata["pixel_format"])- self._last_progress = time.monotonic()- 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),- stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, cwd=self._session_dir)- processes.append(encoder)- # Small bounded queues overlap CPU guides, GPU evaluation and pipe- # writes. Playback seconds are stored as compressed HLS, not RGBA.- incoming: queue.Queue = queue.Queue(maxsize=options.queue_frames)- outgoing: queue.Queue = queue.Queue(maxsize=options.queue_frames)- threads = [threading.Thread(target=self._decode, args=(decoder, incoming, out_w, out_h), daemon=True),- threading.Thread(target=self._encode, args=(encoder, outgoing, out_w, out_h), daemon=True)]- for thread in threads:- thread.start()- put(outgoing, get(incoming, self.controller.cancel), self.controller.cancel)- self._ready.set()- processing_start = time.perf_counter()- pacing_seconds = 0.0- processed = 0- while not self.controller.cancel.is_set():- item = get(incoming, self.controller.cancel)- if item is None:- self.effects.finish()- put(outgoing, None, self.controller.cancel)- break- if isinstance(item, VideoFrame):- self._update_playback()- pacing_seconds += self._pace(item.pts)- request = self.effects.take_due()- if request:- native, output, cost = self._replace_effects(native, request, native_args, item, processed)- else:- start = time.perf_counter()- output, pts = native.process(index=processed, rgba=item.rgba,- reset=item.reset, pts=item.pts)- cost = time.perf_counter() - start- if pts != item.pts:- raise RuntimeError("Neural Rendering bridge returned a different frame timestamp.")- processed += 1- if processed == 1:- evidence = verify_feature_18(native.bridge_logs, native.structured_status())- self._feature_evidence = dict(evidence)- if self._first_frame_at is None:- self._first_frame_at = time.monotonic()- info = self.snapshot()- self._rate.observe(cost, info.guide_ms / 1000, info.encode_ms / 1000)- self._set(processed_frames=processed, dlss_ms=cost * 1000 if processed == 1 or request else- info.dlss_ms * 0.9 + cost * 100, target_fps=self._rate.fps,- effective_fps=processed / max(time.perf_counter() - processing_start - pacing_seconds, 0.001))- item = VideoFrame(item.index, item.pts, item.duration, output)- put(outgoing, item, self.controller.cancel)- self._last_progress = time.monotonic()- for thread in threads:- # Check progress and player closure while the last segment drains.- while thread.is_alive() and not self.controller.cancel.is_set():- thread.join(timeout=0.2)- self._update_playback()- if self._error:- raise RuntimeError(self._error)- if self.controller.cancel.is_set():- raise Cancelled("Live stopped.")- self._finished = True- except Exception as exc:- if not self.controller.cancel.is_set():- self._error = _redact(str(exc))- self.controller.stop()- raise- finally:- watchdog_done.set()- if native is not None:- self._remember_native(native)- native.abort()- for process in processes:- if process.poll() is None:- process.terminate()- try:- process.wait(timeout=5)- except subprocess.TimeoutExpired:- process.kill()- process.wait(timeout=5)- self.controller.unregister(process)- # Errors/Stop unblock queue operations as well as pipe reads/writes.- for thread in threads:- thread.join(timeout=2)- for process in processes:- for pipe in (process.stdin, process.stdout, process.stderr):- if pipe and not pipe.closed:- try:- pipe.close()- except OSError:- pass- watchdog.join(timeout=1)-+ if cuda_path:+ self._produce_cuda(+ resolved, metadata, in_w, in_h, out_w, out_h, factor, mode,+ prepared_runtime, gpu, ordinal,+ )+ return+ native = None+ processes: list[subprocess.Popen] = []+ threads: list[threading.Thread] = []+ watchdog_done = threading.Event()+ self._last_progress = time.monotonic()+ watchdog = threading.Thread(target=self._watchdog, args=(watchdog_done,), daemon=True)+ watchdog.start()+ try:+ 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),+ composition_mask=options.nr_mask,+ controller=self.controller)+ native.diagnostics.encode_backend = "nvenc" if nvenc else "cpu"+ native.diagnostics.source_format = str(metadata["pixel_format"])+ self._last_progress = time.monotonic()+ 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),+ stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, cwd=self._session_dir)+ processes.append(encoder)+ # Small bounded queues overlap CPU guides, GPU evaluation and pipe+ # writes. Playback seconds are stored as compressed HLS, not RGBA.+ incoming: queue.Queue = queue.Queue(maxsize=options.queue_frames)+ outgoing: queue.Queue = queue.Queue(maxsize=options.queue_frames)+ threads = [threading.Thread(target=self._decode, args=(decoder, incoming, out_w, out_h), daemon=True),+ threading.Thread(target=self._encode, args=(encoder, outgoing, out_w, out_h), daemon=True)]+ for thread in threads:+ thread.start()+ put(outgoing, get(incoming, self.controller.cancel), self.controller.cancel)+ self._ready.set()+ processing_start = time.perf_counter()+ pacing_seconds = 0.0+ processed = 0+ while not self.controller.cancel.is_set():+ item = get(incoming, self.controller.cancel)+ if item is None:+ self.effects.finish()+ put(outgoing, None, self.controller.cancel)+ break+ if isinstance(item, VideoFrame):+ self._update_playback()+ pacing_seconds += self._pace(item.pts)+ request = self.effects.take_due()+ if request:+ native, output, cost = self._replace_effects(native, request, native_args, item, processed)+ else:+ start = time.perf_counter()+ output, pts = native.process(index=processed, rgba=item.rgba,+ reset=item.reset, pts=item.pts)+ cost = time.perf_counter() - start+ if pts != item.pts:+ raise RuntimeError("Neural Rendering bridge returned a different frame timestamp.")+ processed += 1+ if processed == 1:+ evidence = verify_feature_18(native.bridge_logs, native.structured_status())+ self._feature_evidence = dict(evidence)+ if self._first_frame_at is None:+ self._first_frame_at = time.monotonic()+ info = self.snapshot()+ self._rate.observe(cost, info.guide_ms / 1000, info.encode_ms / 1000)+ self._set(processed_frames=processed, dlss_ms=cost * 1000 if processed == 1 or request else+ info.dlss_ms * 0.9 + cost * 100, target_fps=self._rate.fps,+ effective_fps=processed / max(time.perf_counter() - processing_start - pacing_seconds, 0.001))+ item = VideoFrame(item.index, item.pts, item.duration, output)+ put(outgoing, item, self.controller.cancel)+ self._last_progress = time.monotonic()+ for thread in threads:+ # Check progress and player closure while the last segment drains.+ while thread.is_alive() and not self.controller.cancel.is_set():+ thread.join(timeout=0.2)+ self._update_playback()+ if self._error:+ raise RuntimeError(self._error)+ if self.controller.cancel.is_set():+ raise Cancelled("Live stopped.")+ self._finished = True+ except Exception as exc:+ if not self.controller.cancel.is_set():+ self._error = _redact(str(exc))+ self.controller.stop()+ raise+ finally:+ watchdog_done.set()+ if native is not None:+ self._remember_native(native)+ native.abort()+ for process in processes:+ if process.poll() is None:+ process.terminate()+ try:+ process.wait(timeout=5)+ except subprocess.TimeoutExpired:+ process.kill()+ process.wait(timeout=5)+ self.controller.unregister(process)+ # Errors/Stop unblock queue operations as well as pipe reads/writes.+ for thread in threads:+ thread.join(timeout=2)+ for process in processes:+ for pipe in (process.stdin, process.stdout, process.stderr):+ if pipe and not pipe.closed:+ try:+ pipe.close()+ except OSError:+ pass+ watchdog.join(timeout=1)+def _write_report(self) -> None:# Reporting is now a single compact session-log line (see run()).# Kept as a no-op for existing callers.- return-- def run(self) -> None:- started = time.monotonic()- self._started_at = started- server = None- try:- validate_options(self.options)- LIVE_DIR.mkdir(parents=True, exist_ok=True)- stamp = time.strftime("%Y%m%d-%H%M%S") + f"-{time.time_ns() % 1_000_000:06d}-{os.getpid()}"- self._session_dir = LIVE_DIR / f"live-{stamp}"- self._session_dir.mkdir()+ return++ def run(self) -> None:+ started = time.monotonic()+ self._started_at = started+ server = None+ try:+ validate_options(self.options)+ LIVE_DIR.mkdir(parents=True, exist_ok=True)+ stamp = time.strftime("%Y%m%d-%H%M%S") + f"-{time.time_ns() % 1_000_000:06d}-{os.getpid()}"+ self._session_dir = LIVE_DIR / f"live-{stamp}"+ self._session_dir.mkdir()(self._session_dir / "owner.json").write_text(json.dumps({"pid": os.getpid(), "keep": self.options.keep_files}))self._set(report_path="")app_log.info("live", f"start src={_redact(self.options.source)[:60]}")- server = HlsServer(self._session_dir)- server.start()- self._set(playlist_url=server.playlist_url())- with active_job(self.controller):- self._produce()- self._set(processing=False)- self._update_playback(finished=True)- self._produced.set()- self._write_report()- # The server and final segments belong to playback, not GPU work.- # Manual players can continue using the URL until Stop is pressed.- while not self.controller.cancel.wait(0.25):- self._update_playback(finished=True)+ server = HlsServer(self._session_dir)+ server.start()+ self._set(playlist_url=server.playlist_url())+ with active_job(self.controller):+ self._produce()+ self._set(processing=False)+ self._update_playback(finished=True)+ self._produced.set()+ self._write_report()+ # The server and final segments belong to playback, not GPU work.+ # Manual players can continue using the URL until Stop is pressed.+ while not self.controller.cancel.wait(0.25):+ self._update_playback(finished=True)if self._mpv and self._mpv.poll() is not None:if self._mpv.returncode:tail = mpv_tail(self._mpv)@@ -978,132 +980,132 @@ class LiveSession(threading.Thread):self._set(report_path=str(err_path), status=f"Failed: {error}", failures=[error])else:app_log.info("live", "cancelled")- self._set(status="Stopped.")- finally:- self.effects.finish()- self.controller.terminate_processes()- if self._mpv and self._mpv.poll() is None:- self._mpv.terminate()- try:- self._mpv.wait(timeout=5)- except subprocess.TimeoutExpired:- self._mpv.kill()- self._mpv.wait(timeout=5)- if server:- server.stop()- self._set(running=False, processing=False, mpv_running=False, playlist_url="",- elapsed_seconds=time.monotonic() - started)+ self._set(status="Stopped.")+ finally:+ self.effects.finish()+ self.controller.terminate_processes()+ if self._mpv and self._mpv.poll() is None:+ self._mpv.terminate()+ try:+ self._mpv.wait(timeout=5)+ except subprocess.TimeoutExpired:+ self._mpv.kill()+ self._mpv.wait(timeout=5)+ if server:+ server.stop()+ self._set(running=False, processing=False, mpv_running=False, playlist_url="",+ elapsed_seconds=time.monotonic() - started)if self._finished and not self.snapshot().failures:self._set(status=f"Finished: {self._title}. {self.info.processed_frames} frames enhanced.")app_log.info("live", f"done frames={self.info.processed_frames} elapsed={self.info.elapsed_seconds:.0f}s")elif not self.snapshot().failures:- self._set(status="Stopped.")- self._write_report()- if self._session_dir and not self.options.keep_files:- shutil.rmtree(self._session_dir, ignore_errors=True)- self._ready.set()- self._produced.set()- with _LOCK:- global _CURRENT, _LAST- _LAST = self.snapshot()- if _CURRENT is self:- _CURRENT = None---def start_live_session(options: LiveOptions) -> LiveSessionInfo:- try:- validate_options(options)- kind = _classify(options.source)- except ValueError as exc:- raise RuntimeError(str(exc)) from exc- check_live_binaries(resolve_pages=kind in ("youtube", "twitch"), play=options.open_mpv)- global _CURRENT- with _LOCK:- if _CURRENT is not None and _CURRENT.is_alive():- raise RuntimeError("A Live session is already running; Stop it first.")- session = LiveSession(options)- _CURRENT = session- session.start()- # Resolution, probe and native setup are cancellable background work.- return session.snapshot()---def stop_live_session(timeout: float | None = 3) -> LiveSessionInfo:- with _LOCK:- session = _CURRENT- if session is None or not session.is_alive():- return live_status()- session.stop()- session.join(timeout=timeout)- return session.snapshot()---def update_live_effects(settings) -> bool:- """Called in shared-settings commit order; enqueue only, never do GPU work."""- with _LOCK:- session = _CURRENT- return session.request_effects(settings) if session is not None else False---def is_live_running() -> bool:- with _LOCK:- return _CURRENT is not None and _CURRENT.is_alive()---def live_status() -> LiveSessionInfo:- with _LOCK:- session, last = _CURRENT, _LAST- return session.snapshot() if session else replace(last, failures=list(last.failures)) if last else LiveSessionInfo()---def sweep_stale_live_dirs() -> int:- """Keep diagnostics and other running app instances' playback intact."""- removed = 0- if not LIVE_DIR.is_dir():- return 0- for child in LIVE_DIR.glob("live-*"):- if not child.is_dir():- continue- try:- owner = json.loads((child / "owner.json").read_text())- if owner.get("keep"):- continue- pid = int(owner["pid"])- # On Windows os.kill(pid, 0) is not a safe process-existence check.- if os.name == "nt":- import ctypes- kernel = ctypes.WinDLL("kernel32", use_last_error=True)- kernel.OpenProcess.restype = ctypes.c_void_p- handle = kernel.OpenProcess(0x1000, False, pid)- if handle:- kernel.CloseHandle.argtypes = [ctypes.c_void_p]- kernel.CloseHandle(handle)- continue- if ctypes.get_last_error() == 5: # access denied implies it exists- continue- else:- try:- os.kill(pid, 0)- continue- except ProcessLookupError:- pass- except PermissionError:- continue- except (OSError, ValueError, KeyError):- # Unknown legacy directories are only swept after a full day.- if time.time() - child.stat().st_mtime < 86400:- continue- shutil.rmtree(child, ignore_errors=True)- removed += not child.exists()- return removed---def _shutdown() -> None:- with _LOCK:- session = _CURRENT- if session:- session.stop()- session.join(timeout=5)--+ self._set(status="Stopped.")+ self._write_report()+ if self._session_dir and not self.options.keep_files:+ shutil.rmtree(self._session_dir, ignore_errors=True)+ self._ready.set()+ self._produced.set()+ with _LOCK:+ global _CURRENT, _LAST+ _LAST = self.snapshot()+ if _CURRENT is self:+ _CURRENT = None+++def start_live_session(options: LiveOptions) -> LiveSessionInfo:+ try:+ validate_options(options)+ kind = _classify(options.source)+ except ValueError as exc:+ raise RuntimeError(str(exc)) from exc+ check_live_binaries(resolve_pages=kind in ("youtube", "twitch"), play=options.open_mpv)+ global _CURRENT+ with _LOCK:+ if _CURRENT is not None and _CURRENT.is_alive():+ raise RuntimeError("A Live session is already running; Stop it first.")+ session = LiveSession(options)+ _CURRENT = session+ session.start()+ # Resolution, probe and native setup are cancellable background work.+ return session.snapshot()+++def stop_live_session(timeout: float | None = 3) -> LiveSessionInfo:+ with _LOCK:+ session = _CURRENT+ if session is None or not session.is_alive():+ return live_status()+ session.stop()+ session.join(timeout=timeout)+ return session.snapshot()+++def update_live_effects(settings) -> bool:+ """Called in shared-settings commit order; enqueue only, never do GPU work."""+ with _LOCK:+ session = _CURRENT+ return session.request_effects(settings) if session is not None else False+++def is_live_running() -> bool:+ with _LOCK:+ return _CURRENT is not None and _CURRENT.is_alive()+++def live_status() -> LiveSessionInfo:+ with _LOCK:+ session, last = _CURRENT, _LAST+ return session.snapshot() if session else replace(last, failures=list(last.failures)) if last else LiveSessionInfo()+++def sweep_stale_live_dirs() -> int:+ """Keep diagnostics and other running app instances' playback intact."""+ removed = 0+ if not LIVE_DIR.is_dir():+ return 0+ for child in LIVE_DIR.glob("live-*"):+ if not child.is_dir():+ continue+ try:+ owner = json.loads((child / "owner.json").read_text())+ if owner.get("keep"):+ continue+ pid = int(owner["pid"])+ # On Windows os.kill(pid, 0) is not a safe process-existence check.+ if os.name == "nt":+ import ctypes+ kernel = ctypes.WinDLL("kernel32", use_last_error=True)+ kernel.OpenProcess.restype = ctypes.c_void_p+ handle = kernel.OpenProcess(0x1000, False, pid)+ if handle:+ kernel.CloseHandle.argtypes = [ctypes.c_void_p]+ kernel.CloseHandle(handle)+ continue+ if ctypes.get_last_error() == 5: # access denied implies it exists+ continue+ else:+ try:+ os.kill(pid, 0)+ continue+ except ProcessLookupError:+ pass+ except PermissionError:+ continue+ except (OSError, ValueError, KeyError):+ # Unknown legacy directories are only swept after a full day.+ if time.time() - child.stat().st_mtime < 86400:+ continue+ shutil.rmtree(child, ignore_errors=True)+ removed += not child.exists()+ return removed+++def _shutdown() -> None:+ with _LOCK:+ session = _CURRENT+ if session:+ session.stop()+ session.join(timeout=5)++atexit.register(_shutdown)diff --git a/src/live/source_resolver.py b/src/live/source_resolver.pyindex 21a63f8..54dc07a 100644--- a/src/live/source_resolver.py+++ b/src/live/source_resolver.py@@ -10,7 +10,7 @@ from urllib.parse import urlparsefrom ..core import app_logfrom ..core.jobs import Cancelled, JobController-from ..core.paths import FFPROBE, YTDLP+from ..core.paths import FFPROBE, YTDLP, APP_TEMPfrom .models import LIVE_SOURCE_QUALITY_CHOICES, ResolvedSource@@ -93,7 +93,8 @@ def resolve_source(raw: str, max_height: int,if not YTDLP.is_file():raise RuntimeError(f"yt-dlp is missing: {YTDLP}")source_height = max_height if source_quality == "Auto" else int(source_quality)- result = run_capture([str(YTDLP), "--no-playlist", "--no-warnings", "--skip-download",+ result = run_capture([str(YTDLP), "--cache-dir", str(APP_TEMP / "yt-dlp"),+ "--no-playlist", "--no-warnings", "--skip-download","--dump-single-json", "--socket-timeout", "15", "--retries", "2", "-f",f"bv*[height<={source_height}]+ba/b[height<={source_height}]/b", text], controller, 90)if result.returncode:diff --git a/src/neural_rendering/image/batch.py b/src/neural_rendering/image/batch.pyindex 5f9405a..86e603e 100644--- a/src/neural_rendering/image/batch.py+++ b/src/neural_rendering/image/batch.py@@ -12,6 +12,7 @@ import cv2import numpy as npfrom ...core.batch_progress import BatchItemUpdate, BatchProgress+from ...core import app_logfrom ...core.disk_paths import OutputFile, prepare_output_dirfrom ...core.dlss_modes import DLSS_MODES, validate_dlssfrom ...core.gpu_selection import resolve_runtime_ai_gpu@@ -30,8 +31,7 @@ from .models import (ImageConversionOptions, ImageConversionResult,)from .reports import (- IncrementalImageArchive, _ImageReportData, _SessionReportData, _build_manifest,- _report_data, _write_report, snapshot_session, update_report_performance,+ IncrementalImageArchive, record_image_result,)@@ -42,10 +42,7 @@ class _OutputTask:output: Pathprocessed: np.ndarraymetadata: dict[str, object]- report_data: _ImageReportData- session_data: _SessionReportData- evidence: dict[str, object]- gpu: dict[str, object]+ gpu_name: strinput_width: intinput_height: intrender_width: int@@ -130,13 +127,13 @@ def _finalize_output(if controller.cancel.is_set():raise Cancelled("Image rendering stopped by user.")- reporter.advance(task.index, .95, "Writing diagnostic report")+ reporter.advance(task.index, .95, "Finalizing image")result = ImageConversionResult(input_path=str(task.path),output_path=str(task.output),report_path="",elapsed_seconds=reporter.elapsed(task.index),- gpu=str(task.gpu["display_name"]),+ gpu=task.gpu_name,input_width=task.input_width,input_height=task.input_height,render_width=task.render_width,@@ -153,22 +150,16 @@ def _finalize_output(warnings=[*task.source_warnings, *warnings],timings=task.timings,)- # Keep the externally reported GPU name identical to the selected GPU.- # The batch caller replaces the temporary value below before report write.- report_started = time.monotonic()- result.report_path = _write_report(- result, options, task.report_data,- task.gpu,- task.session_data, task.evidence,- metadata_diagnostics=metadata_diagnostics,- )- task.timings["report"] = time.monotonic() - report_startedif controller.cancel.is_set():raise Cancelled("Image rendering stopped by user.")publish_started = time.monotonic()output_file.publish()task.timings["publish"] = time.monotonic() - publish_started+ result.elapsed_seconds = reporter.elapsed(task.index)+ report_started = time.monotonic()+ result.report_path = record_image_result(result)+ task.timings["report"] = time.monotonic() - report_started# Archive work is deliberately after publication: cancellation or archive# failure must never roll back a valid completed image.@@ -182,8 +173,6 @@ def _finalize_output(result.elapsed_seconds = reporter.elapsed(task.index)task.timings["total"] = result.elapsed_seconds- with suppress(Exception):- update_report_performance(result)reporter.complete(task.index, str(task.output),"; ".join([*result.warnings, f"Report: {result.report_path}"]),@@ -351,7 +340,7 @@ def convert_images(prep_started = time.monotonic()render_rgba = resize_fit(dlss_rgba if dlss_rgba is not None else decoded.rgba,- session.render_width, session.render_height)+ session.render_width, session.render_height, controller=controller)session.diagnostics.source_format = (f"{decoded.metadata['source_format']}/{decoded.metadata['source_bit_depth']}")@@ -395,8 +384,6 @@ def convert_images()session.diagnostics.output_format = f"{options.output_format}/{output_depth}"- session_data = snapshot_session(session)- evidence_snapshot = dict(session_evidence)render_width = session.render_widthrender_height = session.render_heightresize_method = "dlss" if dlss_details else ("none" if factor == 1.0 else "lanczos")@@ -428,10 +415,7 @@ def convert_images(output=output,processed=processed,metadata=decoded.metadata,- report_data=_report_data(decoded),- session_data=session_data,- evidence=evidence_snapshot,- gpu=dict(gpu),+ gpu_name=str(gpu["display_name"]),input_width=width,input_height=height,render_width=render_width,@@ -512,11 +496,9 @@ def convert_images(zip_path = archive.finish(cancelled=cancelled) if archive is not None else Nonearchive_error = archive.error if archive is not None else None- manifest = _build_manifest(- stamp, options, successes, failures, cancelled,- output_dir=destination,- batch_diagnostics=reporter.diagnostics(final=True),- archive_error=archive_error,+ manifest = app_log.record_batch_summary(+ "image-batch", len(successes), len(failures), cancelled,+ archive_error=archive_error or "",)reporter.finish(cancelled=cancelled, manifest_path=manifest)return ImageBatchResult(successes, failures, cancelled, manifest, zip_path)diff --git a/src/neural_rendering/image/models.py b/src/neural_rendering/image/models.pyindex 49e9d81..df2f36b 100644--- a/src/neural_rendering/image/models.py+++ b/src/neural_rendering/image/models.py@@ -48,7 +48,7 @@ class ImageConversionOptions:class ImageConversionResult:input_path: stroutput_path: str- report_path: str+ report_path: str # Shared session log; field name is kept for existing callers.elapsed_seconds: floatgpu: strinput_width: int@@ -78,5 +78,5 @@ class ImageBatchResult:successes: list[ImageConversionResult]failures: list[ImageConversionFailure]cancelled: bool- manifest_path: str+ manifest_path: str # Shared session log; field name is kept for existing callers.zip_path: str | Nonediff --git a/src/neural_rendering/image/preview.py b/src/neural_rendering/image/preview.pyindex 3303a02..ab8414a 100644--- a/src/neural_rendering/image/preview.py+++ b/src/neural_rendering/image/preview.py@@ -102,6 +102,7 @@ def render_image_preview(render_rgba = resize_fit(dlss_rgba if dlss_rgba is not None else decoded.rgba,session.render_width, session.render_height,+ controller=controller,)session.diagnostics.source_format = (f"{decoded.metadata['source_format']}/{decoded.metadata['source_bit_depth']}"diff --git a/src/neural_rendering/image/reports.py b/src/neural_rendering/image/reports.pyindex 8a33b7b..3fff25d 100644--- a/src/neural_rendering/image/reports.py+++ b/src/neural_rendering/image/reports.py@@ -2,67 +2,16 @@ from __future__ import annotationsimport osimport zipfile-from dataclasses import dataclassfrom pathlib import Pathfrom ...core import app_log-from ...core.paths import OUTPUTSfrom ...core.disk_paths import OutputFilefrom ...core.jobs import Cancelled-from ...core.runtime import DLSSFrameSession-from .decoder import _DecodedImage-from .models import ImageConversionFailure, ImageConversionOptions, ImageConversionResult+from .models import ImageConversionResult-@dataclass(slots=True)-class _ImageReportData:- decoder: str- metadata: dict[str, object]- warnings: list[str]---@dataclass(frozen=True, slots=True)-class _SessionReportData:- minimum_width: int- minimum_height: int- maximum_width: int- maximum_height: int- setup_result: int- native_settings: dict[str, int | float]- runtime_bundle: dict[str, object]- bridge_status: dict[str, object]- bridge_log: tuple[str, ...]---def _report_data(decoded: _DecodedImage) -> _ImageReportData:- """Keep diagnostics without retaining decoded pixel/alpha arrays."""- return _ImageReportData(decoded.decoder, decoded.metadata, list(decoded.warnings))---def snapshot_session(session: DLSSFrameSession) -> _SessionReportData:- """Detach structured report inputs from the live bridge session."""- return _SessionReportData(- minimum_width=session.minimum_width,- minimum_height=session.minimum_height,- maximum_width=session.maximum_width,- maximum_height=session.maximum_height,- setup_result=session.setup_result,- native_settings=dict(session.native_settings),- runtime_bundle=dict(session.runtime_bundle),- bridge_status=session.structured_status(),- bridge_log=tuple(session.bridge_logs),- )---def _write_report(- result: ImageConversionResult,- options: ImageConversionOptions,- decoded: _ImageReportData,- gpu: dict,- session: _SessionReportData,- evidence: dict[str, object],- *, metadata_diagnostics: dict | None = None,-) -> str:+def record_image_result(result: ImageConversionResult) -> str:+ """Record completion and return the shared session log path."""app_log.info("image-render",f"done src={Path(result.input_path).name} out={Path(result.output_path).name} "@@ -71,11 +20,6 @@ def _write_report(return app_log.session_path()-def update_report_performance(result: ImageConversionResult) -> None:- """No-op: per-job report files no longer exist (see session log)."""- return--class IncrementalImageArchive:"""Build the uncompressed batch ZIP while later images are on the GPU."""@@ -140,58 +84,3 @@ class IncrementalImageArchive:passfinally:self.output_file.cleanup(rollback=True)---def _build_manifest(- stamp: str,- options: ImageConversionOptions,- successes: list[ImageConversionResult],- failures: list[ImageConversionFailure],- cancelled: bool,- *, output_dir: Path | None = None, batch_diagnostics: dict | None = None,- archive_error: str | None = None,-) -> str:- status = "cancelled" if cancelled else ("partial" if failures else "success")- app_log.info(- "image-batch",- f"{status} ok={len(successes)} failed={len(failures)}"- + (f" archive_warning={archive_error}" if archive_error else ""),- )- return app_log.session_path()---def _build_manifest_and_zip(- stamp: str,- options: ImageConversionOptions,- successes: list[ImageConversionResult],- failures: list[ImageConversionFailure],- cancelled: bool,- *, create_zip: bool = True, output_dir: Path | None = None, batch_diagnostics: dict | None = None,- controller=None,-) -> tuple[str, str | None]:- """Compatibility helper for callers that do not use IncrementalImageArchive."""- manifest_path = _build_manifest(- stamp, options, successes, failures, cancelled,- output_dir=output_dir, batch_diagnostics=batch_diagnostics,- )- if not successes or not create_zip:- return manifest_path, None- zip_path = (output_dir or OUTPUTS) / f"DLSS5_IMAGE_BATCH_{stamp}.zip"- archive = IncrementalImageArchive(zip_path, controller)- try:- for item in successes:- archive.add(item.output_path)- result = archive.finish(cancelled=cancelled)- if archive.error:- manifest_path = _build_manifest(- stamp, options, successes, failures, cancelled,- output_dir=output_dir, batch_diagnostics=batch_diagnostics,- archive_error=archive.error,- )- return manifest_path, result- except Cancelled:- archive.abort()- return _build_manifest(- stamp, options, successes, failures, True,- output_dir=output_dir, batch_diagnostics=batch_diagnostics,- ), Nonediff --git a/src/neural_rendering/video/batch.py b/src/neural_rendering/video/batch.pyindex 738cb4b..a52ba4c 100644--- a/src/neural_rendering/video/batch.py+++ b/src/neural_rendering/video/batch.py@@ -1,18 +1,17 @@from __future__ import annotationsimport os-import timefrom dataclasses import replacefrom pathlib import Pathfrom typing import Callable, Iterablefrom ...core.batch_progress import BatchItemUpdate, BatchProgress+from ...core import app_logfrom ...core.disk_paths import StreamingMediaArchive, prepare_output_dirfrom ...core.jobs import Cancelled, JobController, active_jobfrom ...core.runtime import prepare_runtimefrom .models import ConversionOptions, VideoBatchResult, VideoConversionFailure, VideoConversionSuccessfrom . import processor-from .reports import _write_video_batch_manifestdef convert_videos(@@ -35,7 +34,6 @@ def convert_videos(archive: StreamingMediaArchive | None = Nonearchive_path: str | None = Nonearchive_error = ""- stamp = time.strftime("%Y%m%d-%H%M%S") + f"-{time.time_ns() % 1_000_000:06d}"try:destination = prepare_output_dir(output_dir, default=processor.OUTPUTS) if not same_as_input or create_archive else Noneif create_archive and len(paths) > 1:@@ -86,12 +84,8 @@ def convert_videos(except Exception as exc:archive_error = str(exc)archive_path = None- diagnostics = reporter.diagnostics(final=True)- if archive_error:- diagnostics["archive_error"] = archive_error- manifest = _write_video_batch_manifest(- stamp, options, successes, failures, cancelled,- batch_diagnostics=diagnostics, output_dir=str(destination) if destination else None+ manifest = app_log.record_batch_summary(+ "video-batch", len(successes), len(failures), cancelled,)reporter.finish(cancelled=cancelled, manifest_path=manifest)return VideoBatchResult(diff --git a/src/neural_rendering/video/cuda_pipeline.py b/src/neural_rendering/video/cuda_pipeline.pyindex a722c60..df4448b 100644--- a/src/neural_rendering/video/cuda_pipeline.py+++ b/src/neural_rendering/video/cuda_pipeline.py@@ -113,7 +113,6 @@ def convert_video_cuda_nvenc(*,preview_seconds: float | None,preview_frames: int | None,- compat_preview: bool,prepared_runtime: Any,controller: Any,progress: Callable[[float, str], None] | None,@@ -157,7 +156,7 @@ def convert_video_cuda_nvenc(dlss_output_size(input_width, input_height, options.dlss_mode, even=True)if options.scale_method == "DLSS" elseresolve_output_size(input_width, input_height, factor))- effective_hdr = bool(options.preserve_hdr and not compat_preview)+ effective_hdr = bool(options.preserve_hdr)output_depth = ffmpeg.output_video_depth(metadata["depth"], options.codec, effective_hdr)output_p010 = output_depth > 8output_color_metadata = dict(metadata)diff --git a/src/neural_rendering/video/models.py b/src/neural_rendering/video/models.pyindex 1912029..2f0d2c5 100644--- a/src/neural_rendering/video/models.py+++ b/src/neural_rendering/video/models.py@@ -1,86 +1,83 @@-from __future__ import annotations--from dataclasses import dataclass--from ...core.runtime import NR_STYLES, UPSCALING_MODES---@dataclass(slots=True)-class ConversionOptions:- ai_gpu_uuid: str = "auto"- video_gpu_uuid: str = "auto"- nr_style: str = "Default"- nr_intensity: float = 1.0- nr_passes: int = 1- local_tone_strength: float = 1.0- local_structure_strength: float = 1.0- skin_structure_strength: float = -1.0- nr_color_strength: float = 1.0- tone_preservation: float = 0.0- face_skin_protection: float = 0.0- grain_preservation: float = 0.0- shimmer_suppression: float = 0.70- mask_feather: int = 0- nr_mask: object | None = None- upscaling_factor: float = 1.0- scale_method: str = "Standard"- dlss_mode: str = "Quality"- dlss_preset: str = "Default"- codec: str = "H.264 (NVIDIA NVENC)"- container: str = "MP4"- quality: str = "Auto (Default)"- preserve_hdr: bool = False- warmup_frames: int = 0- preview_seconds: float | None = None- preview_frames: int | None = None- automatic_mask: bool = False- rename_mode: str = "Auto"- custom_suffix: str = "_Neural_Rendering"- # True = truncated preview uses the forced H.264 SDR path (current behavior).- # False = truncated preview uses the user's codec/container (HDR preserved).- preview_compat: bool = True--@dataclass(slots=True)-class ConversionResult:- output_path: str- report_path: str- frames: int- nr_count_evidence: int- elapsed_seconds: float- gpu: str- input_width: int- input_height: int- render_width: int- render_height: int- output_width: int- output_height: int- upscaling_factor: float- neural_dimensions: dict[str, int] | None = None- resize_method: str = "none"- memory_path: str = "host_cuda_d3d12_shared"- bridge_status: dict | None = None---@dataclass(slots=True)-class VideoConversionSuccess:- index: int- input_path: str- result: ConversionResult---@dataclass(slots=True)-class VideoConversionFailure:- index: int- input_path: str- error: str- cancelled: bool = False---@dataclass(slots=True)-class VideoBatchResult:- successes: list[VideoConversionSuccess]- failures: list[VideoConversionFailure]- cancelled: bool- manifest_path: str- archive_path: str | None = None- archive_error: str = ""+from __future__ import annotations++from dataclasses import dataclass++from ...core.runtime import NR_STYLES, UPSCALING_MODES+++@dataclass(slots=True)+class ConversionOptions:+ ai_gpu_uuid: str = "auto"+ video_gpu_uuid: str = "auto"+ nr_style: str = "Default"+ nr_intensity: float = 1.0+ nr_passes: int = 1+ local_tone_strength: float = 1.0+ local_structure_strength: float = 1.0+ skin_structure_strength: float = -1.0+ nr_color_strength: float = 1.0+ tone_preservation: float = 0.0+ face_skin_protection: float = 0.0+ grain_preservation: float = 0.0+ shimmer_suppression: float = 0.70+ mask_feather: int = 0+ nr_mask: object | None = None+ upscaling_factor: float = 1.0+ scale_method: str = "Standard"+ dlss_mode: str = "Quality"+ dlss_preset: str = "Default"+ codec: str = "H.264"+ container: str = "MP4"+ quality: str = "Auto (Default)"+ preserve_hdr: bool = False+ warmup_frames: int = 0+ preview_seconds: float | None = None+ preview_frames: int | None = None+ automatic_mask: bool = False+ rename_mode: str = "Auto"+ custom_suffix: str = "_Neural_Rendering"++@dataclass(slots=True)+class ConversionResult:+ output_path: str+ report_path: str # Shared session log; field name is kept for existing callers.+ frames: int+ nr_count_evidence: int+ elapsed_seconds: float+ gpu: str+ input_width: int+ input_height: int+ render_width: int+ render_height: int+ output_width: int+ output_height: int+ upscaling_factor: float+ neural_dimensions: dict[str, int] | None = None+ resize_method: str = "none"+ memory_path: str = "host_cuda_d3d12_shared"+ bridge_status: dict | None = None+++@dataclass(slots=True)+class VideoConversionSuccess:+ index: int+ input_path: str+ result: ConversionResult+++@dataclass(slots=True)+class VideoConversionFailure:+ index: int+ input_path: str+ error: str+ cancelled: bool = False+++@dataclass(slots=True)+class VideoBatchResult:+ successes: list[VideoConversionSuccess]+ failures: list[VideoConversionFailure]+ cancelled: bool+ manifest_path: str # Shared session log; field name is kept for existing callers.+ archive_path: str | None = None+ archive_error: str = ""diff --git a/src/neural_rendering/video/preview.py b/src/neural_rendering/video/preview.pyindex c5834a9..da338f5 100644--- a/src/neural_rendering/video/preview.py+++ b/src/neural_rendering/video/preview.py@@ -5,10 +5,8 @@ from pathlib import Pathfrom typing import Callable, Anyfrom ...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 ...core.ffmpeg import probe_video+from ...core.ffmpeg.preview import LOSSLESS_PREVIEW_CODEC, decode_preview_framefrom ...settings.models import coerce_hdr_modefrom .models import ConversionOptionsfrom .processor import convert_video@@ -32,17 +30,16 @@ def process_video_preview(*,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]:+) -> tuple[object | None, str]:"""Qt-native Neural Rendering preview used by the desktop UI.- Returns a plain ``(media_path, status)`` tuple with no UI-framework objects.+ Returns cached video or full-resolution RGBA pixels with a status string."""if not input_path:raise ValueError("Choose a video first.")@@ -59,7 +56,7 @@ def process_video_preview(frame_no = 1effective_source = str(source)temp_clip: str | None = None- if start > 0.05 and (preview_frames is not None or preview_seconds is not None):+ if start > 0 and (preview_frames is not None or preview_seconds 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(@@ -71,32 +68,24 @@ def process_video_preview(effective_source = temp_clipis_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(- options.codec, options.container, preview_encoding_mode- )- compat_preview = wants_compat_preview(- options.codec, options.container, preview_encoding_mode- )+ effective_codec, effective_container = LOSSLESS_PREVIEW_CODEC, "MKV"else:effective_codec, effective_container = options.codec, options.container- compat_preview = False-- effective_hdr = coerce_hdr_mode(effective_codec, options.preserve_hdr) and (- not is_preview or not compat_preview- )- effective = replace(- options,- codec=effective_codec,- container=effective_container,- preserve_hdr=effective_hdr,- preview_seconds=preview_seconds,- preview_frames=preview_frames,- preview_compat=compat_preview,- )try:+ effective_hdr = coerce_hdr_mode(effective_codec, options.preserve_hdr)+ if is_preview:+ effective_hdr = effective_hdr or bool(probe_video(effective_source, count_mode="metadata", controller=controller).get("hdr"))+ effective = replace(+ options,+ codec=effective_codec,+ container=effective_container,+ preserve_hdr=effective_hdr,+ quality="Auto (Default)" if is_preview else options.quality,+ preview_seconds=preview_seconds,+ preview_frames=preview_frames,+ )result = convert_video(effective_source,effective,@@ -113,7 +102,7 @@ def process_video_preview(except OSError:pass- def finish(media_path: str | None, status: str) -> tuple[str | None, str]:+ def finish(media_path: object | None, status: str) -> tuple[object | None, str]:if ephemeral_preview:try:if Path(result.report_path).name.endswith(".report.json"):@@ -121,7 +110,8 @@ def process_video_preview(except OSError:passtry:- if media_path and Path(media_path).resolve() != Path(result.output_path).resolve():+ if media_path is not None and (not isinstance(media_path, (str, Path))+ or Path(media_path).resolve() != Path(result.output_path).resolve()):Path(result.output_path).unlink(missing_ok=True)except OSError:pass@@ -130,30 +120,16 @@ def process_video_preview(source_name = source.nameif is_preview:output_preview = result.output_path- derived_note = ""- 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,- dest_dir=output_dir,- controller=controller,- )- derived_note = " (compatibility preview transcoded to H.264)"- except Exception:- output_preview = result.output_pathif preview_frames is not None:+ if preview_frames == 1:+ output_preview = decode_preview_frame(result.output_path, controller=controller)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}",+ f"{result.memory_path}.",)clip_seconds = preview_seconds if preview_seconds is not None else PREVIEW_SECONDSstart_note = f" from {start:.2f}s" if start > 0.05 else ""@@ -163,20 +139,13 @@ def process_video_preview(f"{clip_seconds:g}-second clip 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.{derived_note}",+ f"{result.memory_path}.",)- output_preview, used_derivative = resolve_final_preview(- result.output_path, preview_encoding_mode, bounded_proxy=True- )status = (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 compatibility proxy was created; the original output is unchanged."- elif output_preview is None:- status += f" {effective_container} output was created successfully, but inline preview is unavailable."- return finish(output_preview, status)+ return finish(result.output_path, status)diff --git a/src/neural_rendering/video/processor.py b/src/neural_rendering/video/processor.pyindex 786e7d7..75a99b4 100644--- a/src/neural_rendering/video/processor.py+++ b/src/neural_rendering/video/processor.py@@ -1,930 +1,924 @@-from __future__ import annotations--import math-import os-import queue-import shutil-import subprocess-import threading-import time-from contextlib import nullcontext, suppress-from dataclasses import replace-from fractions import Fraction-from pathlib import Path-from typing import Callable--import av-import numpy as np--from ...core import app_log, ffmpeg-from ...core.dlss_modes import validate_dlss-from ...core.gpu_selection import resolve_runtime_ai_gpu-from ...core.jobs import Cancelled, active_job-from ...core.naming import output_filename, unique_output_path, validate_rename-from ...core.disk_paths import OutputFile, prepare_output_dir-from ...core.render_metadata import prepare_render_note-from ...core.paths import JOBS, OUTPUTS-from ...core.runtime import (- DLSSFrameSession, prepare_runtime, resize_fit, rotate_frame,-)-from .guides import GuideFrame, TemporalGuideGenerator-from .models import ConversionOptions, ConversionResult-from .sizing import resolve_native_settings, resolve_output_size, resolve_upscaling_mode--validate_codec_container = ffmpeg.validate_codec_container-_BATCH_CONTEXT = threading.local()---def uses_nvenc_frame_boundary(codec: str) -> bool:- """Keep decoded and encoded frames on CUDA when NVENC is selected."""- return ffmpeg._is_nvenc_codec(codec)--def _validate_preview_options(- options: ConversionOptions,-) -> tuple[float | None, int | None]:- preview_seconds: float | None = None- if options.preview_seconds is not None:- try:- preview_seconds = float(options.preview_seconds)- except (TypeError, ValueError) as exc:- raise ValueError("Preview duration must be a positive number of seconds.") from exc- if not math.isfinite(preview_seconds) or preview_seconds <= 0:- raise ValueError("Preview duration must be a positive number of seconds.")-- preview_frames: int | None = None- if options.preview_frames is not None:- if isinstance(options.preview_frames, bool):- raise ValueError("Preview frame count must be a positive integer.")- try:- preview_frames = int(options.preview_frames)- except (TypeError, ValueError) as exc:- raise ValueError("Preview frame count must be a positive integer.") from exc- if preview_frames <= 0 or preview_frames != options.preview_frames:- raise ValueError("Preview frame count must be a positive integer.")- if preview_seconds is not None and preview_frames is not None:- raise ValueError("Choose either a timed preview or a frame preview, not both.")- return preview_seconds, preview_frames---def convert_video(- input_path: str | os.PathLike[str],- options: ConversionOptions | None = None,- progress: Callable[[float, str], None] | None = None,- *, output_dir: str | os.PathLike[str] | None = None, controller=None,-) -> ConversionResult:- options = replace(options) if options is not None else ConversionOptions()- options.container = ffmpeg.container_for_codec(options.codec)- source = Path(input_path).resolve()- if not source.is_file():- raise FileNotFoundError(source)- validate_codec_container(options.codec, options.container)- validate_rename(options.rename_mode, options.custom_suffix)- preview_seconds, preview_frames = _validate_preview_options(options)- is_preview = preview_seconds is not None or preview_frames is not None- # 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))- # The codec selects the frame boundary and encoder. Neural evaluation- # always uses CUDA/D3D12, including the CPU encoder route below.- if options.scale_method not in {"Standard", "DLSS"}:- raise ValueError("Unknown Neural Rendering scale method.")- validate_dlss(options.dlss_mode, options.dlss_preset)- cuda_path = uses_nvenc_frame_boundary(options.codec)- hdr_requested = bool(options.preserve_hdr)- if compat_preview:- hdr_requested = False- if hdr_requested and not ffmpeg.hdr_mode_supported(options.codec):- raise ValueError(- f"HDR Mode is only available for a 10-bit or higher codec; "- f"current codec is {options.codec!r}."- )- prepared_runtime = getattr(_BATCH_CONTEXT, "prepared_runtime", None)- if prepared_runtime is None:- prepared_runtime = prepare_runtime()- batch_controller = getattr(_BATCH_CONTEXT, "controller", None)- job_context = nullcontext(batch_controller) if batch_controller is not None else active_job(controller)-- with job_context as controller:- assert controller is not None- if cuda_path:- from .cuda_pipeline import convert_video_cuda_nvenc-- return convert_video_cuda_nvenc(- source,- options,- preview_seconds=preview_seconds,- preview_frames=preview_frames,- compat_preview=compat_preview,- prepared_runtime=prepared_runtime,- controller=controller,- progress=progress,- output_dir=output_dir,- )- started = time.perf_counter()-- def _report_progress(value: float, desc: str) -> None:- if progress is None:- return- try:- v = float(value)- v = 0.0 if v < 0 else (1.0 if v > 1 else v)- # Status bar shows only the main status; no ETA suffix.- # Native Qt progress callback: progress(value, message).- progress(v, desc)- except Exception:- try:- progress(value, desc)- except Exception:- pass-- timings: dict[str, float] = {}- job_dir: Path | None = None- output: Path | None = None- output_file: OutputFile | None = None- session: DLSSFrameSession | None = None- dlss_session = None- gpu: dict | None = resolve_runtime_ai_gpu(- prepared_runtime.gpus, prepared_runtime.runtime_bundle, options.ai_gpu_uuid- )- video_gpu: dict | None = None- runtime_bundle: dict | None = prepared_runtime.runtime_bundle- encoder = None- encoder_setup_thread: threading.Thread | None = None- producer_thread: threading.Thread | None = None- writer_thread: threading.Thread | None = None- pipeline_stop = threading.Event()- pipeline_errors: queue.Queue[BaseException] = queue.Queue(maxsize=4)- producer_stats: dict[str, float | int | str] = {}- writer_stats: dict[str, float | int] = {}- frame_accounting: dict[str, object] = {"source_verification": "not_required"}-- def record_pipeline_error(exc: BaseException) -> None:- pipeline_stop.set()- try:- pipeline_errors.put_nowait(exc)- except queue.Full:- pass-- try:- stage_started = time.perf_counter()- metadata = ffmpeg.probe_video(source, count_mode="metadata", controller=controller)- color_space = str(metadata.get("color_space") or "").casefold()- color_matrix = 2 if "2020" in color_space else (- 0 if color_space in {"bt470bg", "smpte170m", "smpte240m", "fcc"} else 1- )- color_range = int(- str(metadata.get("color_range") or "").casefold() in {"pc", "jpeg", "full"}- )- chroma_location = ffmpeg.chroma_location_code(metadata)- declared_frames = int(metadata["frames"])- estimated_frames = declared_frames or max(- 1, int(math.ceil(float(metadata["duration"]) * float(metadata["fps"])))- )- if preview_frames is not None:- estimated_frames = min(estimated_frames, preview_frames) if declared_frames else preview_frames- elif preview_seconds is not None:- estimated_frames = min(estimated_frames, max(- 1, int(math.ceil(preview_seconds * float(metadata["fps"])))- ))- frame_accounting.update(- declared_frames=declared_frames, estimated_frames=estimated_frames,- metadata_corrected=False,- )- timings["probe_seconds"] = time.perf_counter() - stage_started- input_width = int(metadata["width"])- input_height = int(metadata["height"])- if options.scale_method == "DLSS":- from ...core.dlss_bridge import DLSSSession- dlss_session = DLSSSession(- input_width, input_height, options.dlss_mode, options.dlss_preset,- gpu_uuid=options.ai_gpu_uuid, even=True)- output_width, output_height = dlss_session.output_width, dlss_session.output_height- factor, mode = resolve_upscaling_mode(1.0)- else:- factor, mode = resolve_upscaling_mode(options.upscaling_factor)- output_width, output_height = resolve_output_size(- input_width, input_height, factor)- effective_hdr = hdr_requested and (not is_preview or not compat_preview)- hdr_metadata = {- "color_space": metadata.get("color_space", "unknown"),- "color_primaries": metadata.get("color_primaries", "unknown"),- "color_transfer": metadata.get("color_transfer", "unknown"),- "color_range": metadata.get("color_range", "unknown"),- "hdr": bool(metadata.get("hdr", False)),- }- output_depth = ffmpeg.output_video_depth(metadata["depth"], options.codec, effective_hdr)- output_color_metadata = dict(hdr_metadata)- if not effective_hdr:- for field in ("color_space", "color_primaries", "color_transfer"):- if output_color_metadata.get(field) in (None, "", "unknown", "unspecified"):- output_color_metadata[field] = "bt709"- if options.codec == "FFV1 Lossless RGB 10-bit":- # The FFV1 branch carries full-range GBR samples. Container- # metadata must describe that output, not the source YUV range.- # FFmpeg's CLI does not accept `-colorspace gbr`; the FFV1- # bitstream already carries GBR from the setparams filter.- output_color_metadata["color_space"] = "unknown"- output_color_metadata["color_range"] = "pc"- destination = prepare_output_dir(output_dir, default=OUTPUTS)- JOBS.mkdir(exist_ok=True)- app_log.info("video-render", f"start src={source.name}")- stamp = time.strftime("%Y%m%d-%H%M%S") + f"-{time.time_ns() % 1_000_000:06d}"- job_dir = JOBS / f"{source.stem}-{stamp}-{os.getpid()}"- job_dir.mkdir(parents=True, exist_ok=False)- extension = {"MP4": ".mp4", "MKV": ".mkv", "MOV": ".mov"}.get(- options.container- )- if extension is None:- raise ValueError(f"Unknown output container: {options.container!r}.")- output_kind = (- "DLSS5"- if not is_preview- else (- "DLSS5_PREVIEW_FRAME"- if preview_frames is not None- else "DLSS5_PREVIEW"- )- )- output = unique_output_path(destination / output_filename(- source,- extension,- options.rename_mode,- options.custom_suffix,- f"{source.stem}_{output_kind}_{stamp}",- ))- 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)- metadata_diagnostics: dict = {}- render_note = prepare_render_note(options, metadata_diagnostics)- video_duration = float(metadata.get("video_stream_duration") or 0.0)- direct_mux = (- options.container in {"MP4", "MOV"}- and preview_frames is None- and (preview_seconds is not None or video_duration > 0.0)- and not (effective_hdr and hdr_metadata["hdr"])- and not (output_depth > 8 and options.codec == "AV1")- )- audio_diagnostics: dict = {}- direct_audio_plan = (- ffmpeg.plan_audio_streams(source, options.container, controller)- if direct_mux else None- )- if direct_audio_plan is not None:- audio_diagnostics["streams"] = direct_audio_plan.diagnostics()- direct_comment = (- ffmpeg.prepare_mux_comment(- source, options.container, render_note, metadata_diagnostics, controller- )- if direct_mux and not is_preview else None- )- if direct_mux and is_preview:- metadata_diagnostics.update(status="skipped", reason="preview_fast_path")- encoder_target = output_file.temporary if direct_mux else temp_video- audio_duration = (- float(preview_seconds)- if preview_seconds is not None- else (video_duration if video_duration > 0.0 else None)- )- _report_progress(0.01, "Starting feature 18")-- encoder_setup: list[tuple] = []- encoding_stage_started = time.perf_counter()-- def prepare_encoder() -> None:- nonlocal video_gpu- encoder_started = time.perf_counter()- try:- # The CPU encoder route retains the separate Video- # Processing GPU selection for its output stage.- encoder_gpu_uuid = options.video_gpu_uuid- video_gpu = ffmpeg.resolve_video_gpu(- prepared_runtime.gpus,- encoder_gpu_uuid,- "H.264" if compat_preview else options.codec,- output_width,- output_height,- )- encoder_setup.append(- ffmpeg.start_encoder(- encoder_target,- options.codec,- options.quality,- controller,- output_width,- output_height,- float(metadata["fps"]),- None if video_gpu is None else int(video_gpu["cuda_ordinal"]),- video_gpu is not None,- hdr_mode=effective_hdr,- hdr_metadata=output_color_metadata,- preserve_timestamps=not metadata["cfr"],- speed_profile="preview" if compat_preview else "neural",- source_audio=source if direct_mux else None,- direct_container=options.container if direct_mux else None,- comment=direct_comment,- audio_duration=audio_duration if direct_mux else None,- include_source_metadata=not is_preview,- audio_plan=direct_audio_plan,- output_depth=output_depth,- )- )- except BaseException as exc:- record_pipeline_error(exc)- finally:- timings["encoder_setup_seconds"] = (- time.perf_counter() - encoder_started- )-- encoder_setup_thread = threading.Thread(- target=prepare_encoder, name="dlss5-encoder-setup", daemon=True- )- encoder_setup_thread.start()- preopened_decoder = None- # Final-residual stabilization needs the original RGBA frame after- # composition. Decode stays on the host for this non-NVENC path;- # feature 18 and optical flow still execute on the selected GPU.- session_started = time.perf_counter()- session = DLSSFrameSession(- input_width=output_width if dlss_session else input_width,- input_height=output_height if dlss_session else input_height,- output_width=output_width,- output_height=output_height,- frame_count=None,- warmup_frames=options.warmup_frames,- factor=factor,- mode=mode,- native_settings=native,- composition_mask=options.nr_mask,- gpu=gpu,- runtime_bundle=runtime_bundle,- controller=controller,- )- timings["native_setup_seconds"] = time.perf_counter() - session_started- encoder_setup_thread.join()- encoder_setup_thread = None- timings["setup_seconds"] = max(- timings["native_setup_seconds"],- timings.get("encoder_setup_seconds", 0.0),- )- if not pipeline_errors.empty():- raise pipeline_errors.get_nowait()- if not encoder_setup:- raise RuntimeError("Video encoder did not finish preparing.")- render_width = session.render_width- render_height = session.render_height- session.diagnostics.source_format = str(metadata["pixel_format"])- session.diagnostics.output_format = (- "rgba16le" if int(metadata["depth"]) > 8 else "rgba8"- )- setup_result = session.setup_result- minimum_width = session.minimum_width- minimum_height = session.minimum_height- maximum_width = session.maximum_width- maximum_height = session.maximum_height- _report_progress(- 0.03,- "Preparing video rendering",- )-- (- encoder,- encoder_log_thread,- encoder_logs,- selected_encoder,- encoding_quality,- ) = encoder_setup[0]- assert encoder.stdin is not None-- high_depth = int(metadata["depth"]) > 8- sample_bytes = 2 if high_depth else 1- prepared_bytes = render_width * render_height * 4 * sample_bytes- rendered_bytes = output_width * output_height * 4 * sample_bytes- queue_slots = max(- 1,- min(3, (384 * 1024 * 1024) // max(1, prepared_bytes + rendered_bytes)),- )- prepared_frames: queue.Queue[object] = queue.Queue(maxsize=queue_slots)- rendered_frames: queue.Queue[object] = queue.Queue(maxsize=queue_slots)- output_pool: queue.LifoQueue[np.ndarray] = queue.LifoQueue(maxsize=queue_slots + 1)- for _ in range(queue_slots + 1):- output_pool.put(np.empty((output_height, output_width, 4), dtype=np.uint16 if high_depth else np.uint8))- stop_marker = object()-- def put_pipeline(target: queue.Queue[object], item: object) -> bool:- while not pipeline_stop.is_set():- if controller.cancel.is_set():- return False- try:- target.put(item, timeout=0.1)- return True- except queue.Full:- continue- return False-- def get_reusable(target: queue.LifoQueue[np.ndarray]) -> np.ndarray | None:- while not pipeline_stop.is_set():- if controller.cancel.is_set():- return None- try:- return target.get(timeout=0.1)- except queue.Empty:- if not pipeline_errors.empty():- return None- continue- return None-- def produce_frames() -> None:- producer_started = time.perf_counter()- decoded = 0- container = None- decode_seconds = 0.0- prepare_seconds = 0.0- guide_seconds = 0.0- queue_wait_seconds = 0.0- hardware_frames = 0- software_frames = 0- try:- if preopened_decoder is not None:- container = preopened_decoder- else:- container = av.open(str(source))- stream = container.streams.video[0]- stream.thread_type = "AUTO"- guides = TemporalGuideGenerator(- input_width if dlss_session else render_width,- input_height if dlss_session else render_height)- first_time: float | None = None- rate = float(stream.average_rate or 30)- default_duration = max(- 1,- round(Fraction(1, 1) / metadata["rate"] / metadata["time_base"]),- )- decoder = iter(container.decode(stream))- while True:- if controller.cancel.is_set():- raise Cancelled("Render stopped by user.")- if pipeline_stop.is_set():- return- # Check a frame-count preview before asking the decoder for- # another frame. The old for-loop decoded one unnecessary- # frame for every one-frame preview.- if preview_frames is not None and decoded >= preview_frames:- producer_stats["completion_reason"] = "preview_limit"- break- decode_started = time.perf_counter()- try:- frame = next(decoder)- except StopIteration:- decode_seconds += time.perf_counter() - decode_started- producer_stats["completion_reason"] = "eof"- break- decode_seconds += time.perf_counter() - decode_started- index = decoded- pts = int(- frame.pts if frame.pts is not None else decoded * default_duration- )- if preview_seconds is not None:- timestamp = float(Fraction(pts) * metadata["time_base"])- if first_time is None:- first_time = timestamp- if decoded and timestamp - first_time >= preview_seconds:- producer_stats["completion_reason"] = "preview_limit"- break- if frame.is_corrupt:- raise RuntimeError(- f"The video decoder marked source frame {index} as corrupt."- )- if frame.format.name == "cuda" and dlss_session is None:- hardware_frames += 1- guide_started = time.perf_counter()- scene_score, reset = session.score_cuda_frame(- frame, color_matrix=color_matrix, color_range=color_range- )- guide = GuideFrame(reset=reset, scene_score=scene_score)- guide_seconds += time.perf_counter() - guide_started- prepared = frame- else:- software_frames += 1- prepare_started = time.perf_counter()- rgba = rotate_frame(- ffmpeg.decoded_rgba(frame, metadata["depth"]), metadata["rotation"]- )- if dlss_session is None and (rgba.shape[1] != render_width or rgba.shape[0] != render_height):- rgba = resize_fit(rgba, render_width, render_height)- rgba = np.ascontiguousarray(rgba)- prepare_seconds += time.perf_counter() - prepare_started- guide_started = time.perf_counter()- guide = guides.process(rgba)- guide_seconds += time.perf_counter() - guide_started- prepared = rgba- duration = int(getattr(frame, "duration", None) or default_duration)- queue_started = time.perf_counter()- queued = put_pipeline(- prepared_frames,- (index, prepared, guide, pts, duration),- )- queue_wait_seconds += time.perf_counter() - queue_started- if not queued:- return- decoded += 1- put_pipeline(prepared_frames, stop_marker)- producer_stats["duplicate_frames"] = guides.duplicate_frames- except BaseException as exc:- record_pipeline_error(exc)- put_pipeline(prepared_frames, stop_marker)- finally:- producer_stats["decoded_frames"] = decoded- producer_stats["decode_seconds"] = decode_seconds- producer_stats["frame_prepare_seconds"] = prepare_seconds- producer_stats["guide_seconds"] = guide_seconds- producer_stats["queue_wait_seconds"] = queue_wait_seconds- producer_stats["hardware_frames"] = hardware_frames- producer_stats["software_frames"] = software_frames- if container is not None:- with suppress(Exception):- container.close()- producer_stats["seconds"] = time.perf_counter() - producer_started-- def write_frames() -> None:- writer_started = time.perf_counter()- written = 0- queue_wait_seconds = 0.0- mux_seconds = 0.0- nut = None- try:- nut = ffmpeg.RawVideoPacketMuxer(- encoder.stdin,- width=output_width,- height=output_height,- rate=metadata["rate"],- time_base=metadata["time_base"],- pix_fmt="rgba64le" if high_depth else "rgba",- )- while not pipeline_stop.is_set():- if controller.cancel.is_set():- raise Cancelled("Render stopped by user.")- queue_started = time.perf_counter()- try:- item = rendered_frames.get(timeout=0.1)- except queue.Empty:- queue_wait_seconds += time.perf_counter() - queue_started- continue- queue_wait_seconds += time.perf_counter() - queue_started- if item is stop_marker:- break- processed, output_pts, duration = item- try:- mux_started = time.perf_counter()- nut.write(processed, output_pts, duration)- mux_seconds += time.perf_counter() - mux_started- written += 1- finally:- output_pool.put(processed)- if not pipeline_stop.is_set():- nut.close()- nut = None- except BaseException as exc:- record_pipeline_error(exc)- finally:- writer_stats["written_frames"] = written- writer_stats["queue_wait_seconds"] = queue_wait_seconds- writer_stats["raw_mux_seconds"] = mux_seconds- if nut is not None:- with suppress(Exception):- nut.close()- writer_stats["seconds"] = time.perf_counter() - writer_started-- producer_thread = threading.Thread(- target=produce_frames, name="dlss5-video-producer", daemon=True- )- writer_thread = threading.Thread(- target=write_frames, name="dlss5-video-writer", daemon=True- )- producer_thread.start()- writer_thread.start()- delivered = 0- scene_resets = 0- preview_pts_origin: int | None = None- dlss_seconds = 0.0- last_progress_update = 0.0- while True:- if controller.cancel.is_set():- raise Cancelled("Render stopped by user.")- if not pipeline_errors.empty():- raise pipeline_errors.get_nowait()- try:- item = prepared_frames.get(timeout=0.1)- except queue.Empty:- continue- if item is stop_marker:- break- index, prepared, guide, pts, duration = item- scene_resets += int(guide.reset and index != 0)- output_buffer = get_reusable(output_pool)- if output_buffer is None:- if not pipeline_errors.empty():- raise pipeline_errors.get_nowait()- raise Cancelled("Render stopped by user.")- dlss_started = time.perf_counter()- try:- if isinstance(prepared, av.VideoFrame) and prepared.format.name == "cuda":- processed, out_pts = session.process_cuda_frame_to_host(- index=index,- frame=prepared,- reset=guide.reset,- scene_score=guide.scene_score,- pts=pts,- color_matrix=color_matrix,- color_range=color_range,- rotation=int(metadata["rotation"]),- chroma_location=chroma_location,- output_buffer=output_buffer,- )- else:- if dlss_session is not None:- dlss_frame = dlss_session.process(- prepared, reset=guide.reset, phase=index)- levels = 65535 if high_depth else 255- prepared = np.rint(np.clip(- dlss_frame.astype(np.float32), 0, 1) * levels- ).astype(np.uint16 if high_depth else np.uint8)- prepared[..., 3] = levels- processed, out_pts = session.process(- index=index,- rgba=prepared,- reset=guide.reset,- pts=pts,- output_buffer=output_buffer,- )- except BaseException:- output_pool.put(output_buffer)- raise- dlss_seconds += time.perf_counter() - dlss_started- if is_preview:- if preview_pts_origin is None:- preview_pts_origin = out_pts- out_pts -= preview_pts_origin- if not put_pipeline(rendered_frames, (processed, out_pts, duration)):- output_pool.put(processed)- if not pipeline_errors.empty():- raise pipeline_errors.get_nowait()- raise Cancelled("Render stopped by user.")- delivered += 1- frame_accounting["processed_frames"] = delivered- now = time.perf_counter()- if now - last_progress_update >= 0.1:- _report_progress(- 0.04 + 0.84 * min(1.0, delivered / estimated_frames),- "Rendering video frames",- )- last_progress_update = now-- if not delivered:- raise RuntimeError("The input video contains no decodable frames.")- if not put_pipeline(rendered_frames, stop_marker):- if not pipeline_errors.empty():- raise pipeline_errors.get_nowait()- raise Cancelled("Render stopped by user.")- producer_thread.join()- producer_thread = None- writer_thread.join()- writer_thread = None- if not pipeline_errors.empty():- raise pipeline_errors.get_nowait()- frame_accounting.update(- decoded_frames=producer_stats.get("decoded_frames"),- written_frames=writer_stats.get("written_frames"),- completion_reason=producer_stats.get("completion_reason"),- )- if (producer_stats.get("decoded_frames") != delivered- or writer_stats.get("written_frames") != delivered- or producer_stats.get("completion_reason") not in {"eof", "preview_limit"}):- raise RuntimeError(f"Video pipeline did not deliver every decoded frame: {frame_accounting}")- timings["producer_seconds"] = float(producer_stats.get("seconds", 0.0))- timings["decode_and_guide_seconds"] = timings["producer_seconds"]- timings["source_decode_seconds"] = float(producer_stats.get("decode_seconds", 0.0))- timings["frame_prepare_seconds"] = float(producer_stats.get("frame_prepare_seconds", 0.0))- timings["guide_seconds"] = float(producer_stats.get("guide_seconds", 0.0))- timings["producer_queue_wait_seconds"] = float(producer_stats.get("queue_wait_seconds", 0.0))- timings["dlss_seconds"] = dlss_seconds- timings["encoder_feed_seconds"] = float(writer_stats.get("seconds", 0.0))- timings["raw_nut_mux_seconds"] = float(writer_stats.get("raw_mux_seconds", 0.0))- timings["writer_queue_wait_seconds"] = float(writer_stats.get("queue_wait_seconds", 0.0))- if encoder.stdin and not encoder.stdin.closed:- encoder.stdin.close()- session.close()- for name, value in session.process_timings.items():- timings[f"native_{name}"] = float(value)- frame_accounting["bridge_completed_frames"] = session.completed_frames- frame_accounting["duplicate_frames"] = int(producer_stats.get("duplicate_frames", 0))- if session.completed_frames != delivered:- raise RuntimeError("Bridge completion does not match the processed frame count.")- encoder_code = encoder.wait(timeout=120)- encoder_log_thread.join(timeout=2)- controller.unregister(encoder)- timings["encoding_seconds"] = time.perf_counter() - encoding_stage_started- if encoder_code:- raise RuntimeError(- "Video encoder failed:\n" + "\n".join(encoder_logs[-40:])- )-- # Reaching clean EOF in the decoder, successful one-for-one pipeline- # accounting, the native END acknowledgement, and a successful encoder- # exit are authoritative. Do not decode the complete source a second- # time just because its container omitted or misreported nb_frames.- if producer_stats["completion_reason"] == "eof":- frame_accounting["source_verification"] = "clean_decoder_eof"- frame_accounting["metadata_corrected"] = bool(- declared_frames and declared_frames != delivered- )- else:- frame_accounting["source_verification"] = "preview_limit"- timings["source_verification_seconds"] = 0.0-- hardware_frames = int(producer_stats.get("hardware_frames", 0))- software_frames = int(producer_stats.get("software_frames", 0))- session.diagnostics.decode_backend = (- "nvdec" if hardware_frames and not software_frames else- "software" if software_frames and not hardware_frames else- "nvdec+software"- )- session.diagnostics.encode_backend = selected_encoder- nr_count = delivered- resize_method = "dlss" if dlss_session else ("none" if factor == 1.0 else "lanczos")- memory_path = session.diagnostics.memory_path- mux_started = time.perf_counter()- if direct_mux:- # MP4/MOV are encoded together with source audio/metadata in the- # same FFmpeg pass, eliminating the complete intermediate-video- # write/read/remux cycle.- _report_progress(0.93, "Finalizing direct audio/video mux")- ffmpeg.verify_mux_comment(- output_file.temporary, direct_comment, metadata_diagnostics, controller- )- timings["final_mux_seconds"] = 0.0- elif preview_frames is not None:- # A frame preview is a visual test, not a production master. The- # encoder already wrote the requested container; avoid reopening the- # source for audio/chapters/metadata and remuxing a one-frame file.- _report_progress(0.93, "Finalizing one-frame preview")- shutil.copyfile(temp_video, output_file.temporary)- metadata_diagnostics.update(status="skipped", reason="preview_fast_path")- timings["final_mux_seconds"] = 0.0- else:- _report_progress(0.91, "Muxing original audio and metadata")- ffmpeg.final_mux(- temp_video, source, output_file.temporary, options.container, controller,- render_note=render_note, metadata_diagnostics=metadata_diagnostics,- audio_diagnostics=audio_diagnostics,- video_color_metadata=output_color_metadata if output_depth > 8 else None,- )- timings["final_mux_seconds"] = time.perf_counter() - mux_started- timings["muxing_seconds"] = timings["final_mux_seconds"]-- # Header/stream verification is enough on the normal success path. The- # application already counted every decoded, DLSS-returned and written- # frame; scanning or decoding the finished file again is pure O(file) I/O.- verify_started = time.perf_counter()- _report_progress(0.96, "Verifying saved output")- verified = ffmpeg.probe_video(- output_file.temporary, count_mode="metadata", controller=controller- )- declared_output_frames = int(verified.get("frames") or 0)- frame_accounting["verified_output_frames"] = (- declared_output_frames if declared_output_frames else delivered- )- frame_accounting["output_verification"] = (- "container_frame_count" if declared_output_frames else "pipeline_accounting"- )- if declared_output_frames and declared_output_frames != delivered:- raise RuntimeError(- f"Output container reports {declared_output_frames} frames instead of "- f"{delivered}."- )- if (verified["width"], verified["height"]) != (- output_width,- output_height,- ):- raise RuntimeError(- f"Output verification found {verified['width']}×{verified['height']} "- f"instead of {output_width}×{output_height}."- )- expected = {- "ProRes HQ": ("prores", "yuv422p10le", 10),- "FFV1 Lossless RGB 10-bit": ("ffv1", "gbrp10le", 10),- }.get(ffmpeg._normalize_codec(options.codec))- if expected and not compat_preview and (- verified.get("codec"), verified.get("pixel_format"),- int(verified.get("depth") or 0)- ) != expected:- raise RuntimeError(f"Saved output does not match {options.codec}.")- if expected and effective_hdr and metadata.get("hdr") and (- not verified.get("hdr") or verified.get("color_primaries") != "bt2020" or- verified.get("color_space") != (- "gbr" if expected[0] == "ffv1" else "bt2020nc")- ):- raise RuntimeError(f"Saved {options.codec} output lost HDR color signaling.")- timings["verification_seconds"] = time.perf_counter() - verify_started-- elapsed = time.perf_counter() - started- report_path = app_log.session_path()- if controller.cancel.is_set():- app_log.info("video-render", f"cancelled src={source.name} frames={delivered}")- raise Cancelled("Render stopped by user.")- app_log.info(- "video-render",- f"done src={source.name} out={output.name} frames={delivered} "- f"elapsed={elapsed:.0f}s avg={delivered / max(elapsed, 1e-9):.1f}fps",- )- output_file.publish()- _report_progress(1.0, "Complete — feature 18 confirmed")- return ConversionResult(- output_path=str(output), report_path=report_path, frames=delivered,- nr_count_evidence=nr_count, elapsed_seconds=elapsed,- gpu=gpu["display_name"], input_width=input_width,- input_height=input_height, render_width=render_width,- render_height=render_height, output_width=output_width,- output_height=output_height,- upscaling_factor=(output_width / input_width if dlss_session else factor),- neural_dimensions={"width": render_width, "height": render_height},- resize_method=resize_method, memory_path=memory_path,- bridge_status={**session.structured_status(),- **({"dlss_super_resolution": {- "mode": options.dlss_mode, "preset": options.dlss_preset,- "guides": "estimated", "frames": dlss_session.frames,- "scene_cuts": scene_resets,- "render_width": dlss_session.last_result.render_width,- "render_height": dlss_session.last_result.render_height,- "gpu_pre_resize": (- dlss_session.last_result.render_width,- dlss_session.last_result.render_height) != (input_width, input_height),- }} if dlss_session else {}),- "timings": dict(timings),- "audio_streams": audio_diagnostics.get("streams", [])},- )- except Exception as exc:- was_cancelled = controller.cancel.is_set()- pipeline_stop.set()- if controller.cancel.is_set():- controller.stop()- else:- controller.terminate_processes()- for target in (prepared_frames if "prepared_frames" in locals() else None,- rendered_frames if "rendered_frames" in locals() else None):- if target is not None:- with suppress(queue.Full):- target.put_nowait(stop_marker)- for thread in (encoder_setup_thread, producer_thread, writer_thread):- if thread is not None:- thread.join(timeout=2)- if session is not None and not session.closed:- with suppress(Exception):- session.abort()- if encoder is not None and encoder.stdin and not encoder.stdin.closed:- with suppress(OSError):- encoder.stdin.close()- if output_file is not None:- output_file.cleanup(rollback=True)- if was_cancelled and not isinstance(exc, Cancelled):- raise Cancelled("Render stopped by user.") from exc- if isinstance(exc, Cancelled):- app_log.info("video-render", f"cancelled src={source.name}")- raise- tails: dict[str, object] = {}- if session is not None:- with suppress(Exception):- tails["bridge"] = session.bridge_logs[-20:]- if "encoder_logs" in locals() and encoder_logs:- tails["ffmpeg"] = list(encoder_logs)[-40:]- report_path = app_log.fail("video-render", f"video-render-{source.stem}", exc, tails or None)- raise RuntimeError(f"{exc}\nDetails: {report_path}") from exc- finally:- if dlss_session is not None:- dlss_session.close()- if output_file is not None:- output_file.cleanup()- pipeline_stop.set()- # Also reap encoders from a failed parallel setup, before `encoder`- # has been assigned. Pipes/log readers must not outlive the job.- encoder_resources = encoder_setup[0] if "encoder_setup" in locals() and encoder_setup else None- if encoder_resources is not None:- encoder_process, log_thread = encoder_resources[:2]- if encoder_process.poll() is None:- encoder_process.terminate()- try:- encoder_process.wait(timeout=5)- except subprocess.TimeoutExpired:- encoder_process.kill()- encoder_process.wait(timeout=5)- log_thread.join(timeout=2)- controller.unregister(encoder_process)- for stream in (encoder_process.stdin, encoder_process.stdout, encoder_process.stderr):- if stream is not None and not stream.closed:- with suppress(OSError):- stream.close()- if job_dir and job_dir.exists():- shutil.rmtree(job_dir, ignore_errors=True)- if "preopened_decoder" in locals() and preopened_decoder is not None:- with suppress(Exception):- preopened_decoder.close()+from __future__ import annotations++import math+import os+import queue+import shutil+import subprocess+import threading+import time+from contextlib import nullcontext, suppress+from dataclasses import replace+from fractions import Fraction+from pathlib import Path+from typing import Callable++import av+from ...core.ffmpeg.frames import open_video_decoder, VideoOutput+import numpy as np++from ...core import app_log, ffmpeg+from ...core.dlss_modes import validate_dlss+from ...core.gpu_selection import resolve_runtime_ai_gpu+from ...core.jobs import Cancelled, active_job+from ...core.naming import output_filename, unique_output_path, validate_rename+from ...core.disk_paths import OutputFile, prepare_output_dir+from ...core.render_metadata import prepare_render_note+from ...core.paths import JOBS, OUTPUTS+from ...core.runtime import (+ DLSSFrameSession, prepare_runtime, resize_fit, rotate_frame,+)+from .guides import GuideFrame, TemporalGuideGenerator+from .models import ConversionOptions, ConversionResult+from .sizing import resolve_native_settings, resolve_output_size, resolve_upscaling_mode++validate_codec_container = ffmpeg.validate_codec_container+_BATCH_CONTEXT = threading.local()+++def uses_nvenc_frame_boundary(codec: str) -> bool:+ """Keep decoded and encoded frames on CUDA when NVENC is selected."""+ return ffmpeg._is_nvenc_codec(codec)++def _validate_preview_options(+ options: ConversionOptions,+) -> tuple[float | None, int | None]:+ preview_seconds: float | None = None+ if options.preview_seconds is not None:+ try:+ preview_seconds = float(options.preview_seconds)+ except (TypeError, ValueError) as exc:+ raise ValueError("Preview duration must be a positive number of seconds.") from exc+ if not math.isfinite(preview_seconds) or preview_seconds <= 0:+ raise ValueError("Preview duration must be a positive number of seconds.")++ preview_frames: int | None = None+ if options.preview_frames is not None:+ if isinstance(options.preview_frames, bool):+ raise ValueError("Preview frame count must be a positive integer.")+ try:+ preview_frames = int(options.preview_frames)+ except (TypeError, ValueError) as exc:+ raise ValueError("Preview frame count must be a positive integer.") from exc+ if preview_frames <= 0 or preview_frames != options.preview_frames:+ raise ValueError("Preview frame count must be a positive integer.")+ if preview_seconds is not None and preview_frames is not None:+ raise ValueError("Choose either a timed preview or a frame preview, not both.")+ return preview_seconds, preview_frames+++def convert_video(+ input_path: str | os.PathLike[str],+ options: ConversionOptions | None = None,+ progress: Callable[[float, str], None] | None = None,+ *, output_dir: str | os.PathLike[str] | None = None, controller=None,+) -> ConversionResult:+ options = replace(options) if options is not None else ConversionOptions()+ source = Path(input_path).resolve()+ if not source.is_file():+ raise FileNotFoundError(source)+ validate_codec_container(options.codec, options.container)+ validate_rename(options.rename_mode, options.custom_suffix)+ preview_seconds, preview_frames = _validate_preview_options(options)+ is_preview = preview_seconds is not None or preview_frames is not None+ # The codec selects the frame boundary and encoder. Neural evaluation+ # always uses CUDA/D3D12, including the CPU encoder route below.+ if options.scale_method not in {"Standard", "DLSS"}:+ raise ValueError("Unknown Neural Rendering scale method.")+ validate_dlss(options.dlss_mode, options.dlss_preset)+ cuda_path = uses_nvenc_frame_boundary(options.codec)+ hdr_requested = bool(options.preserve_hdr)+ if hdr_requested and not ffmpeg.hdr_mode_supported(options.codec):+ raise ValueError(+ f"HDR Mode is only available for a 10-bit or higher codec; "+ f"current codec is {options.codec!r}."+ )+ prepared_runtime = getattr(_BATCH_CONTEXT, "prepared_runtime", None)+ if prepared_runtime is None:+ prepared_runtime = prepare_runtime()+ batch_controller = getattr(_BATCH_CONTEXT, "controller", None)+ job_context = nullcontext(batch_controller) if batch_controller is not None else active_job(controller)++ with job_context as controller:+ assert controller is not None+ if cuda_path:+ from .cuda_pipeline import convert_video_cuda_nvenc++ return convert_video_cuda_nvenc(+ source,+ options,+ preview_seconds=preview_seconds,+ preview_frames=preview_frames,+ prepared_runtime=prepared_runtime,+ controller=controller,+ progress=progress,+ output_dir=output_dir,+ )+ started = time.perf_counter()++ def _report_progress(value: float, desc: str) -> None:+ if progress is None:+ return+ try:+ v = float(value)+ v = 0.0 if v < 0 else (1.0 if v > 1 else v)+ # Status bar shows only the main status; no ETA suffix.+ # Native Qt progress callback: progress(value, message).+ progress(v, desc)+ except Exception:+ try:+ progress(value, desc)+ except Exception:+ pass++ timings: dict[str, float] = {}+ job_dir: Path | None = None+ output: Path | None = None+ output_file: OutputFile | None = None+ session: DLSSFrameSession | None = None+ dlss_session = None+ gpu: dict | None = resolve_runtime_ai_gpu(+ prepared_runtime.gpus, prepared_runtime.runtime_bundle, options.ai_gpu_uuid+ )+ video_gpu: dict | None = None+ runtime_bundle: dict | None = prepared_runtime.runtime_bundle+ encoder = None+ encoder_setup_thread: threading.Thread | None = None+ producer_thread: threading.Thread | None = None+ writer_thread: threading.Thread | None = None+ pipeline_stop = threading.Event()+ pipeline_errors: queue.Queue[BaseException] = queue.Queue(maxsize=4)+ producer_stats: dict[str, float | int | str] = {}+ writer_stats: dict[str, float | int] = {}+ frame_accounting: dict[str, object] = {"source_verification": "not_required"}++ def record_pipeline_error(exc: BaseException) -> None:+ pipeline_stop.set()+ try:+ pipeline_errors.put_nowait(exc)+ except queue.Full:+ pass++ try:+ stage_started = time.perf_counter()+ metadata = ffmpeg.probe_video(source, count_mode="metadata", controller=controller)+ color_space = str(metadata.get("color_space") or "").casefold()+ color_matrix = 2 if "2020" in color_space else (+ 0 if color_space in {"bt470bg", "smpte170m", "smpte240m", "fcc"} else 1+ )+ color_range = int(+ str(metadata.get("color_range") or "").casefold() in {"pc", "jpeg", "full"}+ )+ chroma_location = ffmpeg.chroma_location_code(metadata)+ declared_frames = int(metadata["frames"])+ estimated_frames = declared_frames or max(+ 1, int(math.ceil(float(metadata["duration"]) * float(metadata["fps"])))+ )+ if preview_frames is not None:+ estimated_frames = min(estimated_frames, preview_frames) if declared_frames else preview_frames+ elif preview_seconds is not None:+ estimated_frames = min(estimated_frames, max(+ 1, int(math.ceil(preview_seconds * float(metadata["fps"])))+ ))+ frame_accounting.update(+ declared_frames=declared_frames, estimated_frames=estimated_frames,+ metadata_corrected=False,+ )+ timings["probe_seconds"] = time.perf_counter() - stage_started+ input_width = int(metadata["width"])+ input_height = int(metadata["height"])+ if options.scale_method == "DLSS":+ from ...core.dlss_bridge import DLSSSession+ dlss_session = DLSSSession(+ input_width, input_height, options.dlss_mode, options.dlss_preset,+ gpu_uuid=options.ai_gpu_uuid, even=True)+ output_width, output_height = dlss_session.output_width, dlss_session.output_height+ factor, mode = resolve_upscaling_mode(1.0)+ else:+ factor, mode = resolve_upscaling_mode(options.upscaling_factor)+ output_width, output_height = resolve_output_size(+ input_width, input_height, factor)+ effective_hdr = hdr_requested+ hdr_metadata = {+ "color_space": metadata.get("color_space", "unknown"),+ "color_primaries": metadata.get("color_primaries", "unknown"),+ "color_transfer": metadata.get("color_transfer", "unknown"),+ "color_range": metadata.get("color_range", "unknown"),+ "hdr": bool(metadata.get("hdr", False)),+ }+ output_depth = ffmpeg.output_video_depth(metadata["depth"], options.codec, effective_hdr)+ output_color_metadata = dict(hdr_metadata)+ if not effective_hdr:+ for field in ("color_space", "color_primaries", "color_transfer"):+ if output_color_metadata.get(field) in (None, "", "unknown", "unspecified"):+ output_color_metadata[field] = "bt709"+ if options.codec == "FFV1 Lossless RGB 10-bit":+ # The FFV1 branch carries full-range GBR samples. Container+ # metadata must describe that output, not the source YUV range.+ # FFmpeg's CLI does not accept `-colorspace gbr`; the FFV1+ # bitstream already carries GBR from the setparams filter.+ output_color_metadata["color_space"] = "unknown"+ output_color_metadata["color_range"] = "pc"+ destination = prepare_output_dir(output_dir, default=OUTPUTS)+ JOBS.mkdir(exist_ok=True)+ app_log.info("video-render", f"start src={source.name}")+ stamp = time.strftime("%Y%m%d-%H%M%S") + f"-{time.time_ns() % 1_000_000:06d}"+ job_dir = JOBS / f"{source.stem}-{stamp}-{os.getpid()}"+ job_dir.mkdir(parents=True, exist_ok=False)+ extension = {"MP4": ".mp4", "MKV": ".mkv", "MOV": ".mov"}.get(+ options.container+ )+ if extension is None:+ raise ValueError(f"Unknown output container: {options.container!r}.")+ output_kind = (+ "DLSS5"+ if not is_preview+ else (+ "DLSS5_PREVIEW_FRAME"+ if preview_frames is not None+ else "DLSS5_PREVIEW"+ )+ )+ output = unique_output_path(destination / output_filename(+ source,+ extension,+ options.rename_mode,+ options.custom_suffix,+ f"{source.stem}_{output_kind}_{stamp}",+ ))+ 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)+ metadata_diagnostics: dict = {}+ render_note = prepare_render_note(options, metadata_diagnostics)+ video_duration = float(metadata.get("video_stream_duration") or 0.0)+ direct_mux = (+ options.container in {"MP4", "MOV"}+ and preview_frames is None+ and (preview_seconds is not None or video_duration > 0.0)+ and not (effective_hdr and hdr_metadata["hdr"])+ and not (output_depth > 8 and options.codec == "AV1")+ )+ audio_diagnostics: dict = {}+ direct_audio_plan = (+ ffmpeg.plan_audio_streams(source, options.container, controller)+ if direct_mux else None+ )+ if direct_audio_plan is not None:+ audio_diagnostics["streams"] = direct_audio_plan.diagnostics()+ direct_comment = (+ ffmpeg.prepare_mux_comment(+ source, options.container, render_note, metadata_diagnostics, controller+ )+ if direct_mux and not is_preview else None+ )+ if direct_mux and is_preview:+ metadata_diagnostics.update(status="skipped", reason="preview_fast_path")+ encoder_target = output_file.temporary if direct_mux else temp_video+ audio_duration = (+ float(preview_seconds)+ if preview_seconds is not None+ else (video_duration if video_duration > 0.0 else None)+ )+ _report_progress(0.01, "Starting feature 18")++ encoder_setup: list[tuple] = []+ encoding_stage_started = time.perf_counter()++ def prepare_encoder() -> None:+ nonlocal video_gpu+ encoder_started = time.perf_counter()+ try:+ # The CPU encoder route retains the separate Video+ # Processing GPU selection for its output stage.+ encoder_gpu_uuid = options.video_gpu_uuid+ video_gpu = ffmpeg.resolve_video_gpu(+ prepared_runtime.gpus,+ encoder_gpu_uuid,+ options.codec,+ output_width,+ output_height,+ )+ encoder_setup.append(+ ffmpeg.start_encoder(+ encoder_target,+ options.codec,+ options.quality,+ controller,+ output_width,+ output_height,+ float(metadata["fps"]),+ None if video_gpu is None else int(video_gpu["cuda_ordinal"]),+ video_gpu is not None,+ hdr_mode=effective_hdr,+ hdr_metadata=output_color_metadata,+ preserve_timestamps=not metadata["cfr"],+ speed_profile="neural",+ source_audio=source if direct_mux else None,+ direct_container=options.container if direct_mux else None,+ comment=direct_comment,+ audio_duration=audio_duration if direct_mux else None,+ include_source_metadata=not is_preview,+ audio_plan=direct_audio_plan,+ output_depth=output_depth,+ )+ )+ except BaseException as exc:+ record_pipeline_error(exc)+ finally:+ timings["encoder_setup_seconds"] = (+ time.perf_counter() - encoder_started+ )++ encoder_setup_thread = threading.Thread(+ target=prepare_encoder, name="dlss5-encoder-setup", daemon=True+ )+ encoder_setup_thread.start()+ preopened_decoder = None+ # Final-residual stabilization needs the original RGBA frame after+ # composition. Decode stays on the host for this non-NVENC path;+ # feature 18 and optical flow still execute on the selected GPU.+ session_started = time.perf_counter()+ session = DLSSFrameSession(+ input_width=output_width if dlss_session else input_width,+ input_height=output_height if dlss_session else input_height,+ output_width=output_width,+ output_height=output_height,+ frame_count=None,+ warmup_frames=options.warmup_frames,+ factor=factor,+ mode=mode,+ native_settings=native,+ composition_mask=options.nr_mask,+ gpu=gpu,+ runtime_bundle=runtime_bundle,+ controller=controller,+ )+ timings["native_setup_seconds"] = time.perf_counter() - session_started+ encoder_setup_thread.join()+ encoder_setup_thread = None+ timings["setup_seconds"] = max(+ timings["native_setup_seconds"],+ timings.get("encoder_setup_seconds", 0.0),+ )+ if not pipeline_errors.empty():+ raise pipeline_errors.get_nowait()+ if not encoder_setup:+ raise RuntimeError("Video encoder did not finish preparing.")+ render_width = session.render_width+ render_height = session.render_height+ session.diagnostics.source_format = str(metadata["pixel_format"])+ session.diagnostics.output_format = (+ "rgba16le" if int(metadata["depth"]) > 8 else "rgba8"+ )+ setup_result = session.setup_result+ minimum_width = session.minimum_width+ minimum_height = session.minimum_height+ maximum_width = session.maximum_width+ maximum_height = session.maximum_height+ _report_progress(+ 0.03,+ "Preparing video rendering",+ )++ (+ encoder,+ encoder_log_thread,+ encoder_logs,+ selected_encoder,+ encoding_quality,+ ) = encoder_setup[0]+ assert encoder.stdin is not None++ high_depth = int(metadata["depth"]) > 8+ sample_bytes = 2 if high_depth else 1+ prepared_bytes = render_width * render_height * 4 * sample_bytes+ rendered_bytes = output_width * output_height * 4 * sample_bytes+ queue_slots = max(+ 1,+ min(3, (384 * 1024 * 1024) // max(1, prepared_bytes + rendered_bytes)),+ )+ prepared_frames: queue.Queue[object] = queue.Queue(maxsize=queue_slots)+ rendered_frames: queue.Queue[object] = queue.Queue(maxsize=queue_slots)+ output_pool: queue.LifoQueue[np.ndarray] = queue.LifoQueue(maxsize=queue_slots + 1)+ for _ in range(queue_slots + 1):+ output_pool.put(np.empty((output_height, output_width, 4), dtype=np.uint16 if high_depth else np.uint8))+ stop_marker = object()++ def put_pipeline(target: queue.Queue[object], item: object) -> bool:+ while not pipeline_stop.is_set():+ if controller.cancel.is_set():+ return False+ try:+ target.put(item, timeout=0.1)+ return True+ except queue.Full:+ continue+ return False++ def get_reusable(target: queue.LifoQueue[np.ndarray]) -> np.ndarray | None:+ while not pipeline_stop.is_set():+ if controller.cancel.is_set():+ return None+ try:+ return target.get(timeout=0.1)+ except queue.Empty:+ if not pipeline_errors.empty():+ return None+ continue+ return None++ def produce_frames() -> None:+ producer_started = time.perf_counter()+ decoded = 0+ container = None+ decode_seconds = 0.0+ prepare_seconds = 0.0+ guide_seconds = 0.0+ queue_wait_seconds = 0.0+ hardware_frames = 0+ software_frames = 0+ try:+ if preopened_decoder is not None:+ container = preopened_decoder+ else:+ container = open_video_decoder(source, controller, pixel_format="rgba64le" if metadata.get("depth", 8) > 8 else "rgba")+ stream = container.streams.video[0]+ stream.thread_type = "AUTO"+ guides = TemporalGuideGenerator(+ input_width if dlss_session else render_width,+ input_height if dlss_session else render_height)+ first_time: float | None = None+ rate = float(stream.average_rate or 30)+ default_duration = max(+ 1,+ round(Fraction(1, 1) / metadata["rate"] / metadata["time_base"]),+ )+ decoder = iter(container.decode(stream))+ while True:+ if controller.cancel.is_set():+ raise Cancelled("Render stopped by user.")+ if pipeline_stop.is_set():+ return+ # Check a frame-count preview before asking the decoder for+ # another frame. The old for-loop decoded one unnecessary+ # frame for every one-frame preview.+ if preview_frames is not None and decoded >= preview_frames:+ producer_stats["completion_reason"] = "preview_limit"+ break+ decode_started = time.perf_counter()+ try:+ frame = next(decoder)+ except StopIteration:+ decode_seconds += time.perf_counter() - decode_started+ producer_stats["completion_reason"] = "eof"+ break+ decode_seconds += time.perf_counter() - decode_started+ index = decoded+ pts = int(+ round(Fraction(frame.pts) * (frame.time_base or metadata["time_base"]) / metadata["time_base"]) if frame.pts is not None else decoded * default_duration+ )+ if preview_seconds is not None:+ timestamp = float(Fraction(pts) * metadata["time_base"])+ if first_time is None:+ first_time = timestamp+ if decoded and timestamp - first_time >= preview_seconds:+ producer_stats["completion_reason"] = "preview_limit"+ break+ if frame.is_corrupt:+ raise RuntimeError(+ f"The video decoder marked source frame {index} as corrupt."+ )+ if frame.format.name == "cuda" and dlss_session is None:+ hardware_frames += 1+ guide_started = time.perf_counter()+ scene_score, reset = session.score_cuda_frame(+ frame, color_matrix=color_matrix, color_range=color_range+ )+ guide = GuideFrame(reset=reset, scene_score=scene_score)+ guide_seconds += time.perf_counter() - guide_started+ prepared = frame+ else:+ software_frames += 1+ prepare_started = time.perf_counter()+ rgba = rotate_frame(+ ffmpeg.decoded_rgba(frame, metadata["depth"]), metadata["rotation"]+ )+ if dlss_session is None and (rgba.shape[1] != render_width or rgba.shape[0] != render_height):+ rgba = resize_fit(rgba, render_width, render_height, controller=controller)+ rgba = np.ascontiguousarray(rgba)+ prepare_seconds += time.perf_counter() - prepare_started+ guide_started = time.perf_counter()+ guide = guides.process(rgba)+ guide_seconds += time.perf_counter() - guide_started+ prepared = rgba+ duration = int(getattr(frame, "duration", None) or default_duration)+ queue_started = time.perf_counter()+ queued = put_pipeline(+ prepared_frames,+ (index, prepared, guide, pts, duration),+ )+ queue_wait_seconds += time.perf_counter() - queue_started+ if not queued:+ return+ decoded += 1+ put_pipeline(prepared_frames, stop_marker)+ producer_stats["duplicate_frames"] = guides.duplicate_frames+ except BaseException as exc:+ record_pipeline_error(exc)+ put_pipeline(prepared_frames, stop_marker)+ finally:+ producer_stats["decoded_frames"] = decoded+ producer_stats["decode_seconds"] = decode_seconds+ producer_stats["frame_prepare_seconds"] = prepare_seconds+ producer_stats["guide_seconds"] = guide_seconds+ producer_stats["queue_wait_seconds"] = queue_wait_seconds+ producer_stats["hardware_frames"] = hardware_frames+ producer_stats["software_frames"] = software_frames+ if container is not None:+ with suppress(Exception):+ container.close()+ producer_stats["seconds"] = time.perf_counter() - producer_started++ def write_frames() -> None:+ writer_started = time.perf_counter()+ written = 0+ queue_wait_seconds = 0.0+ mux_seconds = 0.0+ nut = None+ try:+ nut = ffmpeg.RawVideoPacketMuxer(+ encoder.stdin,+ width=output_width,+ height=output_height,+ rate=metadata["rate"],+ time_base=metadata["time_base"],+ pix_fmt="rgba64le" if high_depth else "rgba",+ )+ while not pipeline_stop.is_set():+ if controller.cancel.is_set():+ raise Cancelled("Render stopped by user.")+ queue_started = time.perf_counter()+ try:+ item = rendered_frames.get(timeout=0.1)+ except queue.Empty:+ queue_wait_seconds += time.perf_counter() - queue_started+ continue+ queue_wait_seconds += time.perf_counter() - queue_started+ if item is stop_marker:+ break+ processed, output_pts, duration = item+ try:+ mux_started = time.perf_counter()+ nut.write(processed, output_pts, duration)+ mux_seconds += time.perf_counter() - mux_started+ written += 1+ finally:+ output_pool.put(processed)+ if not pipeline_stop.is_set():+ nut.close()+ nut = None+ except BaseException as exc:+ record_pipeline_error(exc)+ finally:+ writer_stats["written_frames"] = written+ writer_stats["queue_wait_seconds"] = queue_wait_seconds+ writer_stats["raw_mux_seconds"] = mux_seconds+ if nut is not None:+ with suppress(Exception):+ nut.close()+ writer_stats["seconds"] = time.perf_counter() - writer_started++ producer_thread = threading.Thread(+ target=produce_frames, name="dlss5-video-producer", daemon=True+ )+ writer_thread = threading.Thread(+ target=write_frames, name="dlss5-video-writer", daemon=True+ )+ producer_thread.start()+ writer_thread.start()+ delivered = 0+ scene_resets = 0+ preview_pts_origin: int | None = None+ dlss_seconds = 0.0+ last_progress_update = 0.0+ while True:+ if controller.cancel.is_set():+ raise Cancelled("Render stopped by user.")+ if not pipeline_errors.empty():+ raise pipeline_errors.get_nowait()+ try:+ item = prepared_frames.get(timeout=0.1)+ except queue.Empty:+ continue+ if item is stop_marker:+ break+ index, prepared, guide, pts, duration = item+ scene_resets += int(guide.reset and index != 0)+ output_buffer = get_reusable(output_pool)+ if output_buffer is None:+ if not pipeline_errors.empty():+ raise pipeline_errors.get_nowait()+ raise Cancelled("Render stopped by user.")+ dlss_started = time.perf_counter()+ try:+ if isinstance(prepared, av.VideoFrame) and prepared.format.name == "cuda":+ processed, out_pts = session.process_cuda_frame_to_host(+ index=index,+ frame=prepared,+ reset=guide.reset,+ scene_score=guide.scene_score,+ pts=pts,+ color_matrix=color_matrix,+ color_range=color_range,+ rotation=int(metadata["rotation"]),+ chroma_location=chroma_location,+ output_buffer=output_buffer,+ )+ else:+ if dlss_session is not None:+ dlss_frame = dlss_session.process(+ prepared, reset=guide.reset, phase=index)+ levels = 65535 if high_depth else 255+ prepared = np.rint(np.clip(+ dlss_frame.astype(np.float32), 0, 1) * levels+ ).astype(np.uint16 if high_depth else np.uint8)+ prepared[..., 3] = levels+ processed, out_pts = session.process(+ index=index,+ rgba=prepared,+ reset=guide.reset,+ pts=pts,+ output_buffer=output_buffer,+ )+ except BaseException:+ output_pool.put(output_buffer)+ raise+ dlss_seconds += time.perf_counter() - dlss_started+ if is_preview:+ if preview_pts_origin is None:+ preview_pts_origin = out_pts+ out_pts -= preview_pts_origin+ if not put_pipeline(rendered_frames, (processed, out_pts, duration)):+ output_pool.put(processed)+ if not pipeline_errors.empty():+ raise pipeline_errors.get_nowait()+ raise Cancelled("Render stopped by user.")+ delivered += 1+ frame_accounting["processed_frames"] = delivered+ now = time.perf_counter()+ if now - last_progress_update >= 0.1:+ _report_progress(+ 0.04 + 0.84 * min(1.0, delivered / estimated_frames),+ f"Rendering video frames: {delivered:,} / {estimated_frames:,} frames",+ )+ last_progress_update = now++ if not delivered:+ raise RuntimeError("The input video contains no decodable frames.")+ if not put_pipeline(rendered_frames, stop_marker):+ if not pipeline_errors.empty():+ raise pipeline_errors.get_nowait()+ raise Cancelled("Render stopped by user.")+ producer_thread.join()+ producer_thread = None+ writer_thread.join()+ writer_thread = None+ if not pipeline_errors.empty():+ raise pipeline_errors.get_nowait()+ frame_accounting.update(+ decoded_frames=producer_stats.get("decoded_frames"),+ written_frames=writer_stats.get("written_frames"),+ completion_reason=producer_stats.get("completion_reason"),+ )+ if (producer_stats.get("decoded_frames") != delivered+ or writer_stats.get("written_frames") != delivered+ or producer_stats.get("completion_reason") not in {"eof", "preview_limit"}):+ raise RuntimeError(f"Video pipeline did not deliver every decoded frame: {frame_accounting}")+ timings["producer_seconds"] = float(producer_stats.get("seconds", 0.0))+ timings["decode_and_guide_seconds"] = timings["producer_seconds"]+ timings["source_decode_seconds"] = float(producer_stats.get("decode_seconds", 0.0))+ timings["frame_prepare_seconds"] = float(producer_stats.get("frame_prepare_seconds", 0.0))+ timings["guide_seconds"] = float(producer_stats.get("guide_seconds", 0.0))+ timings["producer_queue_wait_seconds"] = float(producer_stats.get("queue_wait_seconds", 0.0))+ timings["dlss_seconds"] = dlss_seconds+ timings["encoder_feed_seconds"] = float(writer_stats.get("seconds", 0.0))+ timings["raw_nut_mux_seconds"] = float(writer_stats.get("raw_mux_seconds", 0.0))+ timings["writer_queue_wait_seconds"] = float(writer_stats.get("queue_wait_seconds", 0.0))+ if encoder.stdin and not encoder.stdin.closed:+ encoder.stdin.close()+ session.close()+ for name, value in session.process_timings.items():+ timings[f"native_{name}"] = float(value)+ frame_accounting["bridge_completed_frames"] = session.completed_frames+ frame_accounting["duplicate_frames"] = int(producer_stats.get("duplicate_frames", 0))+ if session.completed_frames != delivered:+ raise RuntimeError("Bridge completion does not match the processed frame count.")+ encoder_code = encoder.wait(timeout=120)+ encoder_log_thread.join(timeout=2)+ controller.unregister(encoder)+ timings["encoding_seconds"] = time.perf_counter() - encoding_stage_started+ if encoder_code:+ raise RuntimeError(+ "Video encoder failed:\n" + "\n".join(encoder_logs[-40:])+ )++ # Reaching clean EOF in the decoder, successful one-for-one pipeline+ # accounting, the native END acknowledgement, and a successful encoder+ # exit are authoritative. Do not decode the complete source a second+ # time just because its container omitted or misreported nb_frames.+ if producer_stats["completion_reason"] == "eof":+ frame_accounting["source_verification"] = "clean_decoder_eof"+ frame_accounting["metadata_corrected"] = bool(+ declared_frames and declared_frames != delivered+ )+ else:+ frame_accounting["source_verification"] = "preview_limit"+ timings["source_verification_seconds"] = 0.0++ hardware_frames = int(producer_stats.get("hardware_frames", 0))+ software_frames = int(producer_stats.get("software_frames", 0))+ session.diagnostics.decode_backend = (+ "nvdec" if hardware_frames and not software_frames else+ "software" if software_frames and not hardware_frames else+ "nvdec+software"+ )+ session.diagnostics.encode_backend = selected_encoder+ nr_count = delivered+ resize_method = "dlss" if dlss_session else ("none" if factor == 1.0 else "lanczos")+ memory_path = session.diagnostics.memory_path+ mux_started = time.perf_counter()+ if direct_mux:+ # MP4/MOV are encoded together with source audio/metadata in the+ # same FFmpeg pass, eliminating the complete intermediate-video+ # write/read/remux cycle.+ _report_progress(0.93, "Finalizing direct audio/video mux")+ ffmpeg.verify_mux_comment(+ output_file.temporary, direct_comment, metadata_diagnostics, controller+ )+ timings["final_mux_seconds"] = 0.0+ elif preview_frames is not None:+ # A frame preview is a visual test, not a production master. The+ # encoder already wrote the requested container; avoid reopening the+ # source for audio/chapters/metadata and remuxing a one-frame file.+ _report_progress(0.93, "Finalizing one-frame preview")+ shutil.copyfile(temp_video, output_file.temporary)+ metadata_diagnostics.update(status="skipped", reason="preview_fast_path")+ timings["final_mux_seconds"] = 0.0+ else:+ _report_progress(0.91, "Muxing original audio and metadata")+ ffmpeg.final_mux(+ temp_video, source, output_file.temporary, options.container, controller,+ render_note=render_note, metadata_diagnostics=metadata_diagnostics,+ audio_diagnostics=audio_diagnostics,+ video_color_metadata=output_color_metadata if output_depth > 8 else None,+ )+ timings["final_mux_seconds"] = time.perf_counter() - mux_started+ timings["muxing_seconds"] = timings["final_mux_seconds"]++ # Header/stream verification is enough on the normal success path. The+ # application already counted every decoded, DLSS-returned and written+ # frame; scanning or decoding the finished file again is pure O(file) I/O.+ verify_started = time.perf_counter()+ _report_progress(0.96, "Verifying saved output")+ verified = ffmpeg.probe_video(+ output_file.temporary, count_mode="metadata", controller=controller+ )+ declared_output_frames = int(verified.get("frames") or 0)+ frame_accounting["verified_output_frames"] = (+ declared_output_frames if declared_output_frames else delivered+ )+ frame_accounting["output_verification"] = (+ "container_frame_count" if declared_output_frames else "pipeline_accounting"+ )+ if declared_output_frames and declared_output_frames != delivered:+ raise RuntimeError(+ f"Output container reports {declared_output_frames} frames instead of "+ f"{delivered}."+ )+ if (verified["width"], verified["height"]) != (+ output_width,+ output_height,+ ):+ raise RuntimeError(+ f"Output verification found {verified['width']}×{verified['height']} "+ f"instead of {output_width}×{output_height}."+ )+ expected = {+ "ProRes HQ": ("prores", "yuv422p10le", 10),+ "FFV1 Lossless RGB 10-bit": ("ffv1", "gbrp10le", 10),+ }.get(ffmpeg._normalize_codec(options.codec))+ if expected and (+ verified.get("codec"), verified.get("pixel_format"),+ int(verified.get("depth") or 0)+ ) != expected:+ raise RuntimeError(f"Saved output does not match {options.codec}.")+ if expected and effective_hdr and metadata.get("hdr") and (+ not verified.get("hdr") or verified.get("color_primaries") != "bt2020" or+ verified.get("color_space") != (+ "gbr" if expected[0] == "ffv1" else "bt2020nc")+ ):+ raise RuntimeError(f"Saved {options.codec} output lost HDR color signaling.")+ timings["verification_seconds"] = time.perf_counter() - verify_started++ elapsed = time.perf_counter() - started+ report_path = app_log.session_path()+ if controller.cancel.is_set():+ app_log.info("video-render", f"cancelled src={source.name} frames={delivered}")+ raise Cancelled("Render stopped by user.")+ app_log.info(+ "video-render",+ f"done src={source.name} out={output.name} frames={delivered} "+ f"elapsed={elapsed:.0f}s avg={delivered / max(elapsed, 1e-9):.1f}fps",+ )+ output_file.publish()+ _report_progress(1.0, "Complete — feature 18 confirmed")+ return ConversionResult(+ output_path=str(output), report_path=report_path, frames=delivered,+ nr_count_evidence=nr_count, elapsed_seconds=elapsed,+ gpu=gpu["display_name"], input_width=input_width,+ input_height=input_height, render_width=render_width,+ render_height=render_height, output_width=output_width,+ output_height=output_height,+ upscaling_factor=(output_width / input_width if dlss_session else factor),+ neural_dimensions={"width": render_width, "height": render_height},+ resize_method=resize_method, memory_path=memory_path,+ bridge_status={**session.structured_status(),+ **({"dlss_super_resolution": {+ "mode": options.dlss_mode, "preset": options.dlss_preset,+ "guides": "estimated", "frames": dlss_session.frames,+ "scene_cuts": scene_resets,+ "render_width": dlss_session.last_result.render_width,+ "render_height": dlss_session.last_result.render_height,+ "gpu_pre_resize": (+ dlss_session.last_result.render_width,+ dlss_session.last_result.render_height) != (input_width, input_height),+ }} if dlss_session else {}),+ "timings": dict(timings),+ "audio_streams": audio_diagnostics.get("streams", [])},+ )+ except Exception as exc:+ was_cancelled = controller.cancel.is_set()+ pipeline_stop.set()+ if controller.cancel.is_set():+ controller.stop()+ else:+ controller.terminate_processes()+ for target in (prepared_frames if "prepared_frames" in locals() else None,+ rendered_frames if "rendered_frames" in locals() else None):+ if target is not None:+ with suppress(queue.Full):+ target.put_nowait(stop_marker)+ for thread in (encoder_setup_thread, producer_thread, writer_thread):+ if thread is not None:+ thread.join(timeout=2)+ if session is not None and not session.closed:+ with suppress(Exception):+ session.abort()+ if encoder is not None and encoder.stdin and not encoder.stdin.closed:+ with suppress(OSError):+ encoder.stdin.close()+ if output_file is not None:+ output_file.cleanup(rollback=True)+ if was_cancelled and not isinstance(exc, Cancelled):+ raise Cancelled("Render stopped by user.") from exc+ if isinstance(exc, Cancelled):+ app_log.info("video-render", f"cancelled src={source.name}")+ raise+ tails: dict[str, object] = {}+ if session is not None:+ with suppress(Exception):+ tails["bridge"] = session.bridge_logs[-20:]+ if "encoder_logs" in locals() and encoder_logs:+ tails["ffmpeg"] = list(encoder_logs)[-40:]+ report_path = app_log.fail("video-render", f"video-render-{source.stem}", exc, tails or None)+ raise RuntimeError(f"{exc}\nDetails: {report_path}") from exc+ finally:+ if dlss_session is not None:+ dlss_session.close()+ if output_file is not None:+ output_file.cleanup()+ pipeline_stop.set()+ # Also reap encoders from a failed parallel setup, before `encoder`+ # has been assigned. Pipes/log readers must not outlive the job.+ encoder_resources = encoder_setup[0] if "encoder_setup" in locals() and encoder_setup else None+ if encoder_resources is not None:+ encoder_process, log_thread = encoder_resources[:2]+ if encoder_process.poll() is None:+ encoder_process.terminate()+ try:+ encoder_process.wait(timeout=5)+ except subprocess.TimeoutExpired:+ encoder_process.kill()+ encoder_process.wait(timeout=5)+ log_thread.join(timeout=2)+ controller.unregister(encoder_process)+ for stream in (encoder_process.stdin, encoder_process.stdout, encoder_process.stderr):+ if stream is not None and not stream.closed:+ with suppress(OSError):+ stream.close()+ if job_dir and job_dir.exists():+ shutil.rmtree(job_dir, ignore_errors=True)+ if "preopened_decoder" in locals() and preopened_decoder is not None:+ with suppress(Exception):+ preopened_decoder.close()diff --git a/src/neural_rendering/video/reports.py b/src/neural_rendering/video/reports.pydeleted file mode 100644index 3ef926a..0000000--- a/src/neural_rendering/video/reports.py+++ /dev/null@@ -1,17 +0,0 @@-from __future__ import annotations--from ...core import app_log-from .models import ConversionOptions, VideoConversionFailure, VideoConversionSuccess---def _write_video_batch_manifest(- stamp: str,- options: ConversionOptions,- successes: list[VideoConversionSuccess],- failures: list[VideoConversionFailure],- cancelled: bool,- *, batch_diagnostics: dict | None = None, output_dir: str | None = None,-) -> str:- status = "cancelled" if cancelled else ("partial" if failures else "success")- app_log.info("video-batch", f"{status} ok={len(successes)} failed={len(failures)}")- return app_log.session_path()diff --git a/src/portable.py b/src/portable.pynew file mode 100644index 0000000..2475317--- /dev/null+++ b/src/portable.py@@ -0,0 +1,73 @@+"""Keep process-owned writable state beside the bundled application."""+from __future__ import annotations++import os+import sys+import tempfile+from pathlib import Path+++ROOT = Path(__file__).resolve().parents[1]+TEMP = ROOT / "temp"+UI_SETTINGS_PATH = TEMP / "desktop.ini"+_APP_ROOT_TOKEN = "${APP_ROOT}"+_APP_PATH_PREFIX = "${APP_ROOT}/"+++def encode_app_path(value: str) -> str:+ """Keep references to files inside the bundle valid when it is moved."""+ if not value:+ return value+ path = Path(value)+ if not path.is_absolute():+ return value+ try:+ relative = path.resolve().relative_to(ROOT.resolve())+ except (OSError, ValueError):+ return value+ return _APP_PATH_PREFIX + relative.as_posix() if relative.parts else _APP_ROOT_TOKEN+++def decode_app_path(value: str) -> str:+ if value == _APP_ROOT_TOKEN:+ return str(ROOT)+ if not value.startswith(_APP_PATH_PREFIX):+ return value+ relative = Path(value[len(_APP_PATH_PREFIX):])+ if not relative.parts or relative.is_absolute() or ".." in relative.parts:+ return value+ return str(ROOT / relative)+++def configure_portable_environment(root: Path = ROOT) -> Path:+ """Set child-process and library cache paths before loading Qt or FFmpeg."""+ temp = Path(root).resolve() / "temp"+ scratch = temp / "scratch"+ profile = temp / "profile"+ paths = {+ "TEMP": scratch,+ "TMP": scratch,+ "TMPDIR": scratch,+ "APPDATA": profile / "Roaming",+ "LOCALAPPDATA": profile / "Local",+ "XDG_CONFIG_HOME": profile / "config",+ "XDG_DATA_HOME": profile / "data",+ "XDG_CACHE_HOME": profile / "cache",+ "QML_DISK_CACHE_PATH": temp / "qml-cache",+ "CUDA_CACHE_PATH": temp / "cuda-cache",+ }+ try:+ for path in (temp, temp / "app", *paths.values()):+ path.mkdir(parents=True, exist_ok=True)+ except OSError as exc:+ raise RuntimeError(f"The portable temp folder must be writable: {temp}") from exc+ os.environ.update({key: str(path) for key, path in paths.items()})+ # Qt Quick otherwise writes its automatic shader cache to the real+ # QStandardPaths CacheLocation under AppData on Windows.+ os.environ["QT_DISABLE_SHADER_DISK_CACHE"] = "1"+ os.environ["QSG_RHI_DISABLE_SHADER_DISK_CACHE"] = "1"+ os.environ["PYTHONDONTWRITEBYTECODE"] = "1"+ os.environ["PYTHONNOUSERSITE"] = "1"+ sys.dont_write_bytecode = True+ tempfile.tempdir = None # Re-evaluate TEMP if a caller imported tempfile first.+ return tempdiff --git a/src/settings/migration.py b/src/settings/migration.pyindex d2cc95a..9beb2be 100644--- a/src/settings/migration.py+++ b/src/settings/migration.py@@ -2,6 +2,9 @@ from __future__ import annotationsfrom ..core.ffmpeg import _normalize_codec+# Historical IDs used only to discard removed cards from saved layouts.+RETIRED_STAGE_IDS = frozenset({"denoising"})+_CODEC_ALIAS_TO_CANONICAL = {"HEVC": "H.265","H265": "H.265",diff --git a/src/settings/models.py b/src/settings/models.pyindex 8fa3a22..67e45f4 100644--- a/src/settings/models.py+++ b/src/settings/models.py@@ -1,490 +1,506 @@-from __future__ import annotations--from dataclasses import dataclass, replace-import math-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 ..core.dlss_modes import DLSS_METHODS, validate_dlss-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--QUALITY_CHOICES = ENCODING_QUALITIES-CODEC_CHOICES = FFMPEG_CODEC_CHOICES-CONTAINER_CHOICES = ("MP4", "MKV", "MOV")-IMAGE_FORMAT_CHOICES = ("PNG", "JPEG", "WebP", "AVIF", "TIFF")-IMAGE_16BIT_FORMATS = ("PNG", "TIFF")-IMAGE_BIT_DEPTH_CHOICES = (8, 16)-CONFIG_SECTION = "Settings"-PRESET_FORMAT = "dlss5-visual-enhancer-settings-preset"-PRESET_SCHEMA_VERSION = 18-MAX_PRESET_BYTES = 1024 * 1024--AUTOMATIC_MASK_CHOICES = ("Off", "On")--PREVIEW_ENCODING_CHOICES = ("Auto", "Always H.264", "Disabled")-UPSCALE_MODE_CHOICES = ("Image", "Video")-UPSCALE_PREVIEW_LENGTH_CHOICES = PREVIEW_LENGTH_CHOICES--IMAGE_SCALING_FILTERS = ("Lanczos4", "Area", "Bicubic", "Bilinear", "Nearest")-VIDEO_SCALING_FILTERS = ("Spline36", "Lanczos", "Bicubic", "Area", "Bilinear", "EWA Lanczos")--LEGACY_IMAGE_STAGE_ORDER = ("neural_model", "scale_method", "super_resolution")-LEGACY_VIDEO_STAGE_ORDER = (*LEGACY_IMAGE_STAGE_ORDER, "frame_generation")-PREVIOUS_IMAGE_STAGE_ORDER = ("neural_model", "scale_method", "dlss_super_resolution", "super_resolution")-BEFORE_DENOISING_IMAGE_STAGE_ORDER = (*PREVIOUS_IMAGE_STAGE_ORDER, "coloring")-BEFORE_CAS_IMAGE_STAGE_ORDER = ("denoising", *BEFORE_DENOISING_IMAGE_STAGE_ORDER)-IMAGE_STAGE_ORDER = (*BEFORE_CAS_IMAGE_STAGE_ORDER, "cas_sharpening")-PREVIOUS_VIDEO_STAGE_ORDER = (*PREVIOUS_IMAGE_STAGE_ORDER, "frame_generation")-BEFORE_DENOISING_VIDEO_STAGE_ORDER = (*PREVIOUS_VIDEO_STAGE_ORDER, "coloring")-BEFORE_CAS_VIDEO_STAGE_ORDER = ("denoising", *BEFORE_DENOISING_VIDEO_STAGE_ORDER)-VIDEO_STAGE_ORDER = (*BEFORE_CAS_VIDEO_STAGE_ORDER, "cas_sharpening")-COLORING_MODES = ("Color Match", "LUT")-SHARPENING_METHODS = ("NVIDIA NIS", "AMD CAS")-COLOR_MATCH_SOURCES = ("Input Image", "Selected Image")-LUT_RESOLUTIONS = (33, 65, 129)-LUT_ADJUSTMENT_RANGES = {- "lut_mix": (0, 200),- "lut_exposure": (-3.0, 3.0),- "lut_contrast": (-100, 100),- "lut_highlights": (-100, 100),- "lut_shadows": (-100, 100),- "lut_whites": (-100, 100),- "lut_blacks": (-100, 100),- "lut_midtones": (-100, 100),- "lut_temperature": (-100, 100),- "lut_tint": (-100, 100),- "lut_hue": (-180, 180),- "lut_vibrance": (-100, 100),- "lut_saturation": (-100, 100),-}---def validate_stage_layout(order: tuple[str, ...], enabled: tuple[str, ...], *, video: bool) -> None:- allowed = VIDEO_STAGE_ORDER if video else IMAGE_STAGE_ORDER- if not isinstance(order, tuple) or len(order) != len(allowed) or set(order) != set(allowed):- raise ValueError("Pipeline order must contain each available processing card exactly once.")- if not isinstance(enabled, tuple) or len(enabled) != len(set(enabled)) or not set(enabled) <= set(allowed):- raise ValueError("Pipeline enabled stages contain an unavailable or duplicate card.")+from __future__ import annotations++from dataclasses import dataclass, replace+import math+from types import SimpleNamespace++from ..core.ffmpeg import CODEC_CHOICES as FFMPEG_CODEC_CHOICES, CONTAINER_CHOICES, ENCODING_QUALITIES, HDR_ALLOWED_CODECS, hdr_mode_supported, resolve_container+from ..core.ffmpeg.vulkan import valid_selection+from ..core.cache_video import CACHE_VIDEO_CODECS+from ..core.naming import validate_rename+from ..core.runtime import resolve_native_settings, resolve_upscaling_mode+from ..core.dlss_modes import DLSS_METHODS, validate_dlss+from ..frame_interpolation.models import ENGINE_CHOICES, FPS_CHOICES, PREVIEW_LENGTH_CHOICES+from .migration import RETIRED_STAGE_IDS, _migrate_codec+from ..upscale.video.models import options_from_settings+from ..upscale.image.models import options_from_settings as image_upscale_options++QUALITY_CHOICES = ENCODING_QUALITIES+CODEC_CHOICES = FFMPEG_CODEC_CHOICES+IMAGE_FORMAT_CHOICES = ("PNG", "JPEG", "WebP", "AVIF", "TIFF")+IMAGE_16BIT_FORMATS = ("PNG", "TIFF")+IMAGE_BIT_DEPTH_CHOICES = (8, 16)+CONFIG_SECTION = "Settings"+PRESET_FORMAT = "dlss5-visual-enhancer-settings-preset"+PRESET_SCHEMA_VERSION = 27+MAX_PRESET_BYTES = 1024 * 1024++AUTOMATIC_MASK_CHOICES = ("Off", "On")++UPSCALE_MODE_CHOICES = ("Image", "Video")+UPSCALE_PREVIEW_LENGTH_CHOICES = PREVIEW_LENGTH_CHOICES++IMAGE_SCALING_FILTERS = ("Lanczos4", "Area", "Bicubic", "Bilinear", "Nearest")+VIDEO_SCALING_FILTERS = ("Spline36", "Lanczos", "Bicubic", "Area", "Bilinear")+CACHE_MEMORY_MODES = ("stage", "rolling")++LEGACY_IMAGE_STAGE_ORDER = ("neural_model", "scale_method", "super_resolution")+LEGACY_VIDEO_STAGE_ORDER = (*LEGACY_IMAGE_STAGE_ORDER, "frame_generation")+PREVIOUS_IMAGE_STAGE_ORDER = ("neural_model", "scale_method", "dlss_super_resolution", "super_resolution")+BEFORE_CAS_IMAGE_STAGE_ORDER = (*PREVIOUS_IMAGE_STAGE_ORDER, "coloring")+IMAGE_STAGE_ORDER = (*BEFORE_CAS_IMAGE_STAGE_ORDER, "cas_sharpening")+PREVIOUS_VIDEO_STAGE_ORDER = (*PREVIOUS_IMAGE_STAGE_ORDER, "frame_generation")+BEFORE_CAS_VIDEO_STAGE_ORDER = (*PREVIOUS_VIDEO_STAGE_ORDER, "coloring")+BEFORE_HDR_VIDEO_STAGE_ORDER = (*BEFORE_CAS_VIDEO_STAGE_ORDER, "cas_sharpening")+VIDEO_STAGE_ORDER = (*PREVIOUS_IMAGE_STAGE_ORDER, "rtx_video_hdr", "frame_generation", "coloring", "cas_sharpening")+COLORING_MODES = ("Color Match", "LUT")+SHARPENING_METHODS = ("NVIDIA NIS", "AMD CAS")+COLOR_MATCH_SOURCES = ("Input Image", "Selected Image")+LUT_RESOLUTIONS = (33, 65, 129)+LUT_ADJUSTMENT_RANGES = {+ "lut_mix": (0, 200),+ "lut_exposure": (-3.0, 3.0),+ "lut_contrast": (-100, 100),+ "lut_highlights": (-100, 100),+ "lut_shadows": (-100, 100),+ "lut_whites": (-100, 100),+ "lut_blacks": (-100, 100),+ "lut_midtones": (-100, 100),+ "lut_temperature": (-100, 100),+ "lut_tint": (-100, 100),+ "lut_hue": (-180, 180),+ "lut_vibrance": (-100, 100),+ "lut_saturation": (-100, 100),+}+++def validate_stage_layout(order: tuple[str, ...], enabled: tuple[str, ...], *, video: bool) -> None:+ allowed = VIDEO_STAGE_ORDER if video else IMAGE_STAGE_ORDER+ if not isinstance(order, tuple) or len(order) != len(allowed) or set(order) != set(allowed):+ raise ValueError("Pipeline order must contain each available processing card exactly once.")+ if not isinstance(enabled, tuple) or len(enabled) != len(set(enabled)) or not set(enabled) <= set(allowed):+ raise ValueError("Pipeline enabled stages contain an unavailable or duplicate card.")+++def migrate_stage_layout(order: tuple[str, ...], enabled: tuple[str, ...], *,+ video: bool, scale_method: str, upscale_engine: str,+ upscale_vsr_enabled: bool = True,+ upscale_hdr_enabled: bool = False) -> tuple[tuple[str, ...], tuple[str, ...]]:+ """Upgrade old card layouts while retaining their order and enabled behavior."""+ if len(order) != len(set(order)) or len(enabled) != len(set(enabled)) or not set(enabled) <= set(order):+ raise ValueError("Pipeline order contains unknown or duplicate processing cards.")+ order = tuple(stage for stage in order if stage not in RETIRED_STAGE_IDS)+ enabled = tuple(stage for stage in enabled if stage not in RETIRED_STAGE_IDS)+ def finish(new_order: tuple[str, ...], new_enabled: tuple[str, ...]):+ if video and "rtx_video_hdr" not in new_order:+ position = new_order.index("super_resolution") + 1+ new_order = (*new_order[:position], "rtx_video_hdr", *new_order[position:])+ active = set(new_enabled)+ # The old card could run VSR, HDR, or both. Keep its position and+ # enabled behavior when converting it to two independent cards.+ if "super_resolution" in active:+ if upscale_hdr_enabled:+ active.add("rtx_video_hdr")+ if not upscale_vsr_enabled and upscale_hdr_enabled:+ active.remove("super_resolution")+ new_enabled = tuple(stage for stage in new_order if stage in active)+ validate_stage_layout(new_order, new_enabled, video=video)+ return new_order, new_enabled-def migrate_stage_layout(order: tuple[str, ...], enabled: tuple[str, ...], *,- video: bool, scale_method: str, upscale_engine: str) -> tuple[tuple[str, ...], tuple[str, ...]]:- """Upgrade old card layouts while retaining their order and enabled behavior."""allowed = VIDEO_STAGE_ORDER if video else IMAGE_STAGE_ORDERif set(order) == set(allowed) and len(order) == len(allowed):- validate_stage_layout(order, enabled, video=video)- return order, enabled- before_cas = BEFORE_CAS_VIDEO_STAGE_ORDER if video else BEFORE_CAS_IMAGE_STAGE_ORDER- if len(order) == len(before_cas) and set(order) == set(before_cas):- if len(enabled) != len(set(enabled)) or not set(enabled) <= set(order):- raise ValueError("Pipeline enabled stages contain an unavailable or duplicate card.")- result = (*order, "cas_sharpening"), enabled- validate_stage_layout(*result, video=video)- return result- before_denoising = (BEFORE_DENOISING_VIDEO_STAGE_ORDER if video- else BEFORE_DENOISING_IMAGE_STAGE_ORDER)- if len(order) == len(before_denoising) and set(order) == set(before_denoising):- if len(enabled) != len(set(enabled)) or not set(enabled) <= set(order):- raise ValueError("Pipeline enabled stages contain an unavailable or duplicate card.")- result = ("denoising", *order, "cas_sharpening"), enabled- validate_stage_layout(*result, video=video)- return result- previous = PREVIOUS_VIDEO_STAGE_ORDER if video else PREVIOUS_IMAGE_STAGE_ORDER- if len(order) == len(previous) and set(order) == set(previous):- if len(enabled) != len(set(enabled)) or not set(enabled) <= set(order):- raise ValueError("Pipeline enabled stages contain an unavailable or duplicate card.")- result = ("denoising", *order, "coloring", "cas_sharpening"), enabled- validate_stage_layout(*result, video=video)- return result- old = LEGACY_VIDEO_STAGE_ORDER if video else LEGACY_IMAGE_STAGE_ORDER- if len(order) != len(old) or set(order) != set(old) or len(enabled) != len(set(enabled)) or not set(enabled) <= set(old):- raise ValueError("Pipeline order contains unknown or duplicate processing cards.")- scale_dlss_active = "scale_method" in enabled and scale_method == "DLSS"- upscale_dlss_active = "super_resolution" in enabled and upscale_engine == "DLSS"- if scale_dlss_active and upscale_dlss_active:- dlss_origin = next(stage for stage in order if stage in {"scale_method", "super_resolution"})- elif scale_dlss_active:- dlss_origin = "scale_method"- else:- dlss_origin = "super_resolution"- migrated_order: list[str] = []- for stage in order:- if stage == "scale_method":- if dlss_origin == "scale_method":- migrated_order.append("dlss_super_resolution")- migrated_order.append(stage)- elif stage == "super_resolution":- if dlss_origin == "super_resolution":- migrated_order.append("dlss_super_resolution")- migrated_order.append(stage)- else:- migrated_order.append(stage)- migrated_enabled = set(enabled) - {"scale_method", "super_resolution"}- if "scale_method" in enabled:- migrated_enabled.add("dlss_super_resolution" if scale_method == "DLSS" else "scale_method")- if "super_resolution" in enabled:- migrated_enabled.add("dlss_super_resolution" if upscale_engine == "DLSS" else "super_resolution")- result = tuple(migrated_order), tuple(stage for stage in migrated_order if stage in migrated_enabled)- result = ("denoising", *result[0], "coloring", "cas_sharpening"), result[1]- validate_stage_layout(*result, video=video)- return result---def coerce_hdr_mode(codec: str, enabled: bool) -> bool:- return bool(enabled) and hdr_mode_supported(codec)---def automatic_mask_choice(enabled: bool) -> str:- return "On" if enabled else "Off"---def parse_automatic_mask(value: str) -> bool:- if value not in AUTOMATIC_MASK_CHOICES:- choices = ", ".join(AUTOMATIC_MASK_CHOICES)- raise ValueError(f"Automatic Mask must be one of: {choices}.")- return value == "On"--@dataclass(frozen=True, slots=True)-class UISettings:- image_stage_order: tuple[str, ...] = IMAGE_STAGE_ORDER- video_stage_order: tuple[str, ...] = VIDEO_STAGE_ORDER- image_enabled_stages: tuple[str, ...] = ()- video_enabled_stages: tuple[str, ...] = ()- denoise_strength: int = 50- denoise_deblock: bool = True- denoise_temporal: int = 30- sharpening_method: str = "AMD CAS"- # Legacy key retained so existing CAS settings and presets keep their value.- cas_sharpness: int = 50- coloring_mode: str = "Color Match"- color_match_source: str = "Input Image"- color_match_reference: str = ""+ return finish(order, enabled)+ if video and len(order) == len(BEFORE_HDR_VIDEO_STAGE_ORDER) and set(order) == set(BEFORE_HDR_VIDEO_STAGE_ORDER):+ return finish(order, enabled)+ before_cas = BEFORE_CAS_VIDEO_STAGE_ORDER if video else BEFORE_CAS_IMAGE_STAGE_ORDER+ if len(order) == len(before_cas) and set(order) == set(before_cas):+ result = (*order, "cas_sharpening"), enabled+ return finish(*result)+ previous = PREVIOUS_VIDEO_STAGE_ORDER if video else PREVIOUS_IMAGE_STAGE_ORDER+ if len(order) == len(previous) and set(order) == set(previous):+ result = (*order, "coloring", "cas_sharpening"), enabled+ return finish(*result)+ old = LEGACY_VIDEO_STAGE_ORDER if video else LEGACY_IMAGE_STAGE_ORDER+ if len(order) != len(old) or set(order) != set(old):+ raise ValueError("Pipeline order contains unknown or duplicate processing cards.")+ scale_dlss_active = "scale_method" in enabled and scale_method == "DLSS"+ upscale_dlss_active = "super_resolution" in enabled and upscale_engine == "DLSS"+ if scale_dlss_active and upscale_dlss_active:+ dlss_origin = next(stage for stage in order if stage in {"scale_method", "super_resolution"})+ elif scale_dlss_active:+ dlss_origin = "scale_method"+ else:+ dlss_origin = "super_resolution"+ migrated_order: list[str] = []+ for stage in order:+ if stage == "scale_method":+ if dlss_origin == "scale_method":+ migrated_order.append("dlss_super_resolution")+ migrated_order.append(stage)+ elif stage == "super_resolution":+ if dlss_origin == "super_resolution":+ migrated_order.append("dlss_super_resolution")+ migrated_order.append(stage)+ else:+ migrated_order.append(stage)+ migrated_enabled = set(enabled) - {"scale_method", "super_resolution"}+ if "scale_method" in enabled:+ migrated_enabled.add("dlss_super_resolution" if scale_method == "DLSS" else "scale_method")+ if "super_resolution" in enabled:+ migrated_enabled.add("dlss_super_resolution" if upscale_engine == "DLSS" else "super_resolution")+ result = tuple(migrated_order), tuple(stage for stage in migrated_order if stage in migrated_enabled)+ result = (*result[0], "coloring", "cas_sharpening"), result[1]+ return finish(*result)+++def coerce_hdr_mode(codec: str, enabled: bool) -> bool:+ return bool(enabled) and hdr_mode_supported(codec)+++def automatic_mask_choice(enabled: bool) -> str:+ return "On" if enabled else "Off"+++def parse_automatic_mask(value: str) -> bool:+ if value not in AUTOMATIC_MASK_CHOICES:+ choices = ", ".join(AUTOMATIC_MASK_CHOICES)+ raise ValueError(f"Automatic Mask must be one of: {choices}.")+ return value == "On"++@dataclass(frozen=True, slots=True)+class UISettings:+ image_stage_order: tuple[str, ...] = IMAGE_STAGE_ORDER+ video_stage_order: tuple[str, ...] = VIDEO_STAGE_ORDER+ image_enabled_stages: tuple[str, ...] = ()+ video_enabled_stages: tuple[str, ...] = ()+ sharpening_method: str = "AMD CAS"+ # Legacy key retained so existing CAS settings and presets keep their value.+ cas_sharpness: int = 50+ coloring_mode: str = "Color Match"+ color_match_source: str = "Input Image"+ color_match_reference: str = ""lut_path: str = ""- lut_resolution: int = 33- lut_mix: int = 100- lut_exposure: float = 0.0- lut_contrast: int = 0- lut_highlights: int = 0- lut_shadows: int = 0- lut_whites: int = 0- lut_blacks: int = 0- lut_midtones: int = 0- lut_temperature: int = 0- lut_tint: int = 0- lut_hue: int = 0- lut_vibrance: int = 0- lut_saturation: int = 0- ai_gpu_uuid: str = "auto"- video_gpu_uuid: str = "auto"- nr_style: str = "Default"- nr_intensity: float = 1.0- nr_passes: int = 1- local_tone_strength: float = 1.0- local_structure_strength: float = 1.0- skin_structure_strength: float = -1.0- nr_color_strength: float = 1.0- tone_preservation: float = 0.0- face_skin_protection: float = 0.0- grain_preservation: float = 0.0- # Video/Live temporal residual stabilization. Image rendering always- # remains reset-based and does not consume this value.- shimmer_suppression: float = 0.70- mask_feather: int = 0- # Validated native file-picker identity; intentionally omitted from config/presets.- nr_mask: object | None = None- upscaling_factor: float = 1.0- image_scaling_filter: str = "Lanczos4"- video_scaling_filter: str = "Spline36"- nr_scale_method: str = "Standard"- nr_dlss_mode: str = "Quality"- nr_dlss_preset: str = "Default"- nr_preview_length: str = "3"- # 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)"+ lut_reference_image: str = ""+ lut_resolution: int = 33+ lut_mix: int = 100+ lut_exposure: float = 0.0+ lut_contrast: int = 0+ lut_highlights: int = 0+ lut_shadows: int = 0+ lut_whites: int = 0+ lut_blacks: int = 0+ lut_midtones: int = 0+ lut_temperature: int = 0+ lut_tint: int = 0+ lut_hue: int = 0+ lut_vibrance: int = 0+ lut_saturation: int = 0+ ai_gpu_uuid: str = "auto"+ video_gpu_uuid: str = "auto"+ ffmpeg_device: str = "auto"+ cache_memory_mode: str = "stage"+ cache_codec: str = "FFV1"+ nr_style: str = "Default"+ nr_intensity: float = 1.0+ nr_passes: int = 1+ local_tone_strength: float = 1.0+ local_structure_strength: float = 1.0+ skin_structure_strength: float = -1.0+ nr_color_strength: float = 1.0+ tone_preservation: float = 0.0+ face_skin_protection: float = 0.0+ grain_preservation: float = 0.0+ # Video/Live temporal residual stabilization. Image rendering always+ # remains reset-based and does not consume this value.+ shimmer_suppression: float = 0.70+ mask_feather: int = 0+ # Validated native file-picker identity; intentionally omitted from config/presets.+ nr_mask: object | None = None+ upscaling_factor: float = 1.0+ image_scaling_filter: str = "Lanczos4"+ video_scaling_filter: str = "Spline36"+ nr_scale_method: str = "Standard"+ nr_dlss_mode: str = "Quality"+ nr_dlss_preset: str = "Default"+ nr_preview_length: str = "3"+ # 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"container: str = "MP4"- quality: str = "Auto (Default)"- hdr_mode: bool = False- image_format: str = "PNG"- image_quality: int = 95- image_bit_depth: int = 8- automatic_mask: bool = False- image_rename_mode: str = "Auto"- image_custom_suffix: str = "_Neural_Rendering"- video_rename_mode: str = "Auto"- video_custom_suffix: str = "_Neural_Rendering"- frame_interpolation_target_fps: str = "60"- frame_interpolation_engine: str = "Auto"- # Factory default only. Existing saved selections are loaded unchanged.- frame_interpolation_codec: str = "H.264 (NVIDIA NVENC)"- frame_interpolation_container: str = "MP4"- frame_interpolation_quality: str = "Auto (Default)"- frame_interpolation_hdr_mode: bool = False- frame_interpolation_rename_mode: str = "Auto"- frame_interpolation_custom_suffix: str = "_Frame_Interpolation"- frame_interpolation_preview_length: str = "3"- preview_encoding: str = "Auto"- upscale_mode: str = "Image"- upscale_image_vsr_quality: int = 4- upscale_image_engine: str = "RTX Video Super Resolution"- upscale_image_dlss_mode: str = "Quality"- upscale_image_dlss_preset: str = "Default"- upscale_image_size_mode: str = "Scale factor"- upscale_image_scale_factor: float = 2.0- upscale_image_width: int = 3840- upscale_image_height: int = 2160- upscale_image_aspect_lock: bool = True- upscale_image_output_format: str = "PNG"- upscale_image_quality: int = 95- upscale_image_rename_mode: str = "Auto"- upscale_image_custom_suffix: str = "_Upscale"- upscale_vsr_enabled: bool = True- upscale_engine: str = "RTX Video Super Resolution"- upscale_dlss_mode: str = "Quality"- upscale_dlss_preset: str = "Default"- upscale_vsr_quality: int = 4- upscale_size_mode: str = "Scale factor"- upscale_scale_factor: float = 2.0- upscale_width: int = 3840- upscale_height: int = 2160- upscale_aspect_lock: bool = True- upscale_hdr_enabled: bool = False- upscale_hdr_contrast: int = 100- upscale_hdr_saturation: int = 100- upscale_hdr_middle_gray: int = 50- upscale_hdr_peak_luminance: int = 1000- upscale_hdr_precision: str = "Packed 10-bit"- upscale_codec: str = "H.265 (NVIDIA NVENC)"- upscale_container: str = "MKV"- upscale_quality: str = "Auto (Default)"- upscale_preview_length: str = "3"- upscale_rename_mode: str = "Auto"- upscale_custom_suffix: str = "_Upscale"-- def component_values(- self,- ) -> 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,- self.nr_passes,- self.local_tone_strength,- self.local_structure_strength,- self.skin_structure_strength,- self.nr_color_strength,- self.tone_preservation,- self.face_skin_protection,- self.grain_preservation,- self.shimmer_suppression,- self.mask_feather,- self.upscaling_factor,- self.automatic_mask,- 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()---def _validate(settings: UISettings) -> UISettings:- validate_stage_layout(settings.image_stage_order, settings.image_enabled_stages, video=False)- validate_stage_layout(settings.video_stage_order, settings.video_enabled_stages, video=True)- for name in ("denoise_strength", "denoise_temporal", "cas_sharpness"):- value = getattr(settings, name)- if isinstance(value, bool) or not isinstance(value, int) or not 0 <= value <= 100:- raise ValueError(f"{name} must be an integer from 0 to 100.")- if not isinstance(settings.denoise_deblock, bool):- raise ValueError("Compression artifact cleanup must be a boolean value.")- if settings.sharpening_method not in SHARPENING_METHODS:- raise ValueError(f"Unknown sharpening method: {settings.sharpening_method!r}.")- if settings.coloring_mode not in COLORING_MODES:- raise ValueError(f"Unknown Coloring mode: {settings.coloring_mode!r}.")- if settings.color_match_source not in COLOR_MATCH_SOURCES:- raise ValueError(f"Unknown Color Match source: {settings.color_match_source!r}.")- if not isinstance(settings.color_match_reference, str) or len(settings.color_match_reference) > 4096:- raise ValueError("Color Match reference must be a valid image path.")+ quality: str = "Auto (Default)"+ hdr_mode: bool = False+ image_format: str = "PNG"+ image_quality: int = 95+ image_bit_depth: int = 8+ automatic_mask: bool = False+ image_rename_mode: str = "Auto"+ image_custom_suffix: str = "_Neural_Rendering"+ video_rename_mode: str = "Auto"+ video_custom_suffix: str = "_Neural_Rendering"+ frame_interpolation_target_fps: str = "60"+ frame_interpolation_engine: str = "Auto"+ # Factory default only. Existing saved selections are loaded unchanged.+ frame_interpolation_codec: str = "H.264"+ frame_interpolation_container: str = "MP4"+ frame_interpolation_quality: str = "Auto (Default)"+ frame_interpolation_hdr_mode: bool = False+ frame_interpolation_rename_mode: str = "Auto"+ frame_interpolation_custom_suffix: str = "_Frame_Interpolation"+ frame_interpolation_preview_length: str = "3"+ upscale_mode: str = "Image"+ upscale_image_vsr_quality: int = 4+ upscale_image_engine: str = "RTX Video Super Resolution"+ upscale_image_dlss_mode: str = "Quality"+ upscale_image_dlss_preset: str = "Default"+ upscale_image_size_mode: str = "Scale factor"+ upscale_image_scale_factor: float = 2.0+ upscale_image_width: int = 3840+ upscale_image_height: int = 2160+ upscale_image_aspect_lock: bool = True+ upscale_image_output_format: str = "PNG"+ upscale_image_quality: int = 95+ upscale_image_rename_mode: str = "Auto"+ upscale_image_custom_suffix: str = "_Upscale"+ upscale_vsr_enabled: bool = True+ upscale_engine: str = "RTX Video Super Resolution"+ upscale_dlss_mode: str = "Quality"+ upscale_dlss_preset: str = "Default"+ upscale_vsr_quality: int = 4+ upscale_size_mode: str = "Scale factor"+ upscale_scale_factor: float = 2.0+ upscale_width: int = 3840+ upscale_height: int = 2160+ upscale_aspect_lock: bool = True+ upscale_hdr_enabled: bool = False+ upscale_hdr_contrast: int = 100+ upscale_hdr_saturation: int = 100+ upscale_hdr_middle_gray: int = 50+ upscale_hdr_peak_luminance: int = 1000+ upscale_hdr_precision: str = "Packed 10-bit"+ upscale_codec: str = "H.265"+ upscale_container: str = "MKV"+ upscale_quality: str = "Auto (Default)"+ upscale_preview_length: str = "3"+ upscale_rename_mode: str = "Auto"+ upscale_custom_suffix: str = "_Upscale"++ def component_values(+ self,+ ) -> 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,+ self.nr_passes,+ self.local_tone_strength,+ self.local_structure_strength,+ self.skin_structure_strength,+ self.nr_color_strength,+ self.tone_preservation,+ self.face_skin_protection,+ self.grain_preservation,+ self.shimmer_suppression,+ self.mask_feather,+ self.upscaling_factor,+ self.automatic_mask,+ 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()+++def _validate(settings: UISettings) -> UISettings:+ validate_stage_layout(settings.image_stage_order, settings.image_enabled_stages, video=False)+ validate_stage_layout(settings.video_stage_order, settings.video_enabled_stages, video=True)+ value = settings.cas_sharpness+ if isinstance(value, bool) or not isinstance(value, int) or not 0 <= value <= 100:+ raise ValueError("cas_sharpness must be an integer from 0 to 100.")+ if settings.sharpening_method not in SHARPENING_METHODS:+ raise ValueError(f"Unknown sharpening method: {settings.sharpening_method!r}.")+ if settings.coloring_mode not in COLORING_MODES:+ raise ValueError(f"Unknown Coloring mode: {settings.coloring_mode!r}.")+ if settings.color_match_source not in COLOR_MATCH_SOURCES:+ raise ValueError(f"Unknown Color Match source: {settings.color_match_source!r}.")+ if not isinstance(settings.color_match_reference, str) or len(settings.color_match_reference) > 4096:+ raise ValueError("Color Match reference must be a valid image path.")if not isinstance(settings.lut_path, str) or len(settings.lut_path) > 4096:raise ValueError("LUT must be a valid .cube file path.")- if isinstance(settings.lut_resolution, bool) or settings.lut_resolution not in LUT_RESOLUTIONS:- raise ValueError("LUT resolution must be 33, 65, or 129.")- for name, (minimum, maximum) in LUT_ADJUSTMENT_RANGES.items():- value = getattr(settings, name)- if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value):- raise ValueError(f"{name} must be a finite number.")- if name != "lut_exposure" and (not isinstance(value, int) or isinstance(value, bool)):- raise ValueError(f"{name} must be an integer.")- if not minimum <= value <= maximum:- raise ValueError(f"{name} must be between {minimum} and {maximum}.")- options_from_settings(settings).validate(for_render=False)- image_upscale_options(settings).validate(for_render=False)- for label, value in (- ("AI Processing GPU", settings.ai_gpu_uuid),- ("Video Processing GPU", settings.video_gpu_uuid),- ):- if not isinstance(value, str) or not value.strip() or len(value) > 160:- raise ValueError(f"{label} selection must be Automatic or a valid GPU UUID.")- resolve_native_settings(settings)- if isinstance(settings.nr_passes, bool) or not isinstance(settings.nr_passes, int):- 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)- if settings.image_scaling_filter not in IMAGE_SCALING_FILTERS:- raise ValueError(f"Unknown image scaling filter: {settings.image_scaling_filter!r}.")- if settings.video_scaling_filter not in VIDEO_SCALING_FILTERS:- raise ValueError(f"Unknown video scaling filter: {settings.video_scaling_filter!r}.")- if settings.nr_scale_method not in DLSS_METHODS:- raise ValueError(f"Unknown Neural Rendering scale method: {settings.nr_scale_method!r}.")- validate_dlss(settings.nr_dlss_mode, settings.nr_dlss_preset)- 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.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.lut_reference_image, str) or len(settings.lut_reference_image) > 4096:+ raise ValueError("LUT reference must be a valid image path.")+ if isinstance(settings.lut_resolution, bool) or settings.lut_resolution not in LUT_RESOLUTIONS:+ raise ValueError("LUT resolution must be 33, 65, or 129.")+ for name, (minimum, maximum) in LUT_ADJUSTMENT_RANGES.items():+ value = getattr(settings, name)+ if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value):+ raise ValueError(f"{name} must be a finite number.")+ if name != "lut_exposure" and (not isinstance(value, int) or isinstance(value, bool)):+ raise ValueError(f"{name} must be an integer.")+ if not minimum <= value <= maximum:+ raise ValueError(f"{name} must be between {minimum} and {maximum}.")+ options_from_settings(settings).validate(for_render=False)+ image_upscale_options(settings).validate(for_render=False)+ if not valid_selection(settings.ffmpeg_device):+ raise ValueError("FFmpeg/Vulkan must be Automatic, CPU, or a Vulkan GPU UUID.")+ if settings.cache_memory_mode not in CACHE_MEMORY_MODES:+ raise ValueError("Cache Memory must be Stage by Stage or Rolling Cache (5 GB).")+ if settings.cache_codec not in CACHE_VIDEO_CODECS:+ raise ValueError("Cache Memory codec must be FFV1 or ProRes Proxy.")+ for label, value in (+ ("AI Processing GPU", settings.ai_gpu_uuid),+ ("Video Processing GPU", settings.video_gpu_uuid),+ ):+ if not isinstance(value, str) or not value.strip() or len(value) > 160:+ raise ValueError(f"{label} selection must be Automatic or a valid GPU UUID.")+ resolve_native_settings(settings)+ if isinstance(settings.nr_passes, bool) or not isinstance(settings.nr_passes, int):+ 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)+ if settings.image_scaling_filter not in IMAGE_SCALING_FILTERS:+ raise ValueError(f"Unknown image scaling filter: {settings.image_scaling_filter!r}.")+ if settings.video_scaling_filter not in VIDEO_SCALING_FILTERS:+ raise ValueError(f"Unknown video scaling filter: {settings.video_scaling_filter!r}.")+ if settings.nr_scale_method not in DLSS_METHODS:+ raise ValueError(f"Unknown Neural Rendering scale method: {settings.nr_scale_method!r}.")+ validate_dlss(settings.nr_dlss_mode, settings.nr_dlss_preset)+ 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.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.")- # Migrate old codec names before validation- migrated_codec = _migrate_codec(settings.codec)- migrated_fi_codec = _migrate_codec(settings.frame_interpolation_codec)- if migrated_codec != settings.codec or migrated_fi_codec != settings.frame_interpolation_codec:- settings = replace(settings, codec=migrated_codec, frame_interpolation_codec=migrated_fi_codec)- # HDR Mode is only allowed for 10-bit capable codecs; if enabled with H.264, auto-disable for old configs- # For strict validation (presets), raise if mismatched – caller can decide; here we raise for explicit mismatch- _HDR_ALLOWED = HDR_ALLOWED_CODECS-- if settings.hdr_mode and settings.codec not in _HDR_ALLOWED:- raise ValueError(- f"HDR Mode is only available for {', '.join(sorted(_HDR_ALLOWED))}; current codec is {settings.codec!r}."- )- if settings.frame_interpolation_hdr_mode and settings.frame_interpolation_codec not in _HDR_ALLOWED:- raise ValueError(- f"Frame Interpolation HDR Mode is only available for {', '.join(sorted(_HDR_ALLOWED))}; current codec is {settings.frame_interpolation_codec!r}."- )- allowed = {- "Video codec": (settings.codec, CODEC_CHOICES),- "Container": (settings.container, CONTAINER_CHOICES),- "Encoding quality": (settings.quality, QUALITY_CHOICES),- "Image format": (settings.image_format, IMAGE_FORMAT_CHOICES),- "Frame Interpolation FPS": (- settings.frame_interpolation_target_fps,- FPS_CHOICES,- ),- "Frame Interpolation engine": (- settings.frame_interpolation_engine,- ENGINE_CHOICES,- ),- "Frame Interpolation codec": (- settings.frame_interpolation_codec,- CODEC_CHOICES,- ),- "Frame Interpolation container": (- settings.frame_interpolation_container,- CONTAINER_CHOICES,- ),- "Frame Interpolation quality": (- settings.frame_interpolation_quality,- QUALITY_CHOICES,- ),- "Frame Interpolation preview length": (- settings.frame_interpolation_preview_length,- PREVIEW_LENGTH_CHOICES,- ),- "Upscale preview length": (- settings.upscale_preview_length,- UPSCALE_PREVIEW_LENGTH_CHOICES,- ),- "Neural Rendering preview length": (- settings.nr_preview_length,- PREVIEW_LENGTH_CHOICES,- ),- "Preview encoding": (- settings.preview_encoding,- PREVIEW_ENCODING_CHOICES,- ),- "Upscale mode": (- settings.upscale_mode,- UPSCALE_MODE_CHOICES,- ),- }+ # Migrate old codec names before validation+ migrated_codec = _migrate_codec(settings.codec)+ migrated_fi_codec = _migrate_codec(settings.frame_interpolation_codec)+ if migrated_codec != settings.codec or migrated_fi_codec != settings.frame_interpolation_codec:+ settings = replace(settings, codec=migrated_codec, frame_interpolation_codec=migrated_fi_codec)+ # HDR Mode is only allowed for 10-bit capable codecs; if enabled with H.264, auto-disable for old configs+ # For strict validation (presets), raise if mismatched – caller can decide; here we raise for explicit mismatch+ _HDR_ALLOWED = HDR_ALLOWED_CODECS++ if settings.hdr_mode and settings.codec not in _HDR_ALLOWED:+ raise ValueError(+ f"HDR Mode is only available for {', '.join(sorted(_HDR_ALLOWED))}; current codec is {settings.codec!r}."+ )+ if settings.frame_interpolation_hdr_mode and settings.frame_interpolation_codec not in _HDR_ALLOWED:+ raise ValueError(+ f"Frame Interpolation HDR Mode is only available for {', '.join(sorted(_HDR_ALLOWED))}; current codec is {settings.frame_interpolation_codec!r}."+ )+ allowed = {+ "Video codec": (settings.codec, CODEC_CHOICES),+ "Container": (settings.container, CONTAINER_CHOICES),+ "Encoding quality": (settings.quality, QUALITY_CHOICES),+ "Image format": (settings.image_format, IMAGE_FORMAT_CHOICES),+ "Frame Interpolation FPS": (+ settings.frame_interpolation_target_fps,+ FPS_CHOICES,+ ),+ "Frame Interpolation engine": (+ settings.frame_interpolation_engine,+ ENGINE_CHOICES,+ ),+ "Frame Interpolation codec": (+ settings.frame_interpolation_codec,+ CODEC_CHOICES,+ ),+ "Frame Interpolation container": (+ settings.frame_interpolation_container,+ CONTAINER_CHOICES,+ ),+ "Frame Interpolation quality": (+ settings.frame_interpolation_quality,+ QUALITY_CHOICES,+ ),+ "Frame Interpolation preview length": (+ settings.frame_interpolation_preview_length,+ PREVIEW_LENGTH_CHOICES,+ ),+ "Upscale preview length": (+ settings.upscale_preview_length,+ UPSCALE_PREVIEW_LENGTH_CHOICES,+ ),+ "Neural Rendering preview length": (+ settings.nr_preview_length,+ PREVIEW_LENGTH_CHOICES,+ ),+ "Upscale mode": (+ settings.upscale_mode,+ UPSCALE_MODE_CHOICES,+ ),+ }for label, (value, choices) in allowed.items():if value not in choices:raise ValueError(f"Unknown {label}: {value!r}.")- if isinstance(settings.image_quality, bool) or not 1 <= int(settings.image_quality) <= 100:- raise ValueError("Image quality must be an integer from 1 to 100.")- if int(settings.image_quality) != settings.image_quality:- raise ValueError("Image quality must be an integer from 1 to 100.")- if isinstance(settings.image_bit_depth, bool) or settings.image_bit_depth not in IMAGE_BIT_DEPTH_CHOICES:- raise ValueError("Image bit depth must be 8 or 16 bits.")- if settings.image_bit_depth == 16 and settings.image_format not in IMAGE_16BIT_FORMATS:- raise ValueError("16-bit image output is available for PNG and TIFF only.")- validate_rename(settings.image_rename_mode, settings.image_custom_suffix)- validate_rename(settings.video_rename_mode, settings.video_custom_suffix)- validate_rename(- settings.frame_interpolation_rename_mode,- settings.frame_interpolation_custom_suffix,- )- options_from_settings(settings).validate(for_render=False)- image_upscale_options(settings).validate(for_render=False)- return settings+ for codec, container in (+ (settings.codec, settings.container),+ (settings.frame_interpolation_codec, settings.frame_interpolation_container),+ (settings.upscale_codec, settings.upscale_container),+ ):+ resolve_container(codec, container)+ if isinstance(settings.image_quality, bool) or not 1 <= int(settings.image_quality) <= 100:+ raise ValueError("Image quality must be an integer from 1 to 100.")+ if int(settings.image_quality) != settings.image_quality:+ raise ValueError("Image quality must be an integer from 1 to 100.")+ if isinstance(settings.image_bit_depth, bool) or settings.image_bit_depth not in IMAGE_BIT_DEPTH_CHOICES:+ raise ValueError("Image bit depth must be 8 or 16 bits.")+ if settings.image_bit_depth == 16 and settings.image_format not in IMAGE_16BIT_FORMATS:+ raise ValueError("16-bit image output is available for PNG and TIFF only.")+ validate_rename(settings.image_rename_mode, settings.image_custom_suffix)+ validate_rename(settings.video_rename_mode, settings.video_custom_suffix)+ validate_rename(+ settings.frame_interpolation_rename_mode,+ settings.frame_interpolation_custom_suffix,+ )+ options_from_settings(settings).validate(for_render=False)+ image_upscale_options(settings).validate(for_render=False)+ return settingsdiff --git a/src/settings/presets.py b/src/settings/presets.pyindex f14406d..276f5d9 100644--- a/src/settings/presets.py+++ b/src/settings/presets.py@@ -10,6 +10,8 @@ from pathlib import Pathfrom typing import Anyfrom ..core.paths import APP_TEMP+from ..portable import decode_app_path, encode_app_path+from ..core.ffmpeg import container_for_codecfrom .models import (DEFAULT_SETTINGS, MAX_PRESET_BYTES, PRESET_FORMAT, PRESET_SCHEMA_VERSION, UISettings, _validate,LUT_ADJUSTMENT_RANGES, migrate_stage_layout,@@ -55,6 +57,8 @@ def preset_document(name: str, settings: UISettings) -> dict[str, Any]:_validate(settings)values = asdict(settings)values.pop("nr_mask", None)+ for key in ("color_match_reference", "lut_path", "lut_reference_image"):+ values[key] = encode_app_path(values[key])return {"format": PRESET_FORMAT,"schema_version": PRESET_SCHEMA_VERSION,@@ -146,6 +150,9 @@ def import_settings_preset(for key, value in imported.items()if key in known_names and key != "nr_mask"}+ for key in ("color_match_reference", "lut_path", "lut_reference_image"):+ if key in changes:+ changes[key] = decode_app_path(changes[key])if version == 1:# v1's DLSS model-preset field was never applied by feature 18. Ignore# it. (The retired GPU staging switch from old presets is filtered by@@ -189,6 +196,8 @@ def import_settings_preset(changes[order_key], changes[enabled_key] = migrate_stage_layout(old_order, old_enabled, video=mode == "Video",scale_method=old_scale, upscale_engine=engine,+ upscale_vsr_enabled=changes.get("upscale_vsr_enabled", DEFAULT_SETTINGS.upscale_vsr_enabled),+ upscale_hdr_enabled=changes.get("upscale_hdr_enabled", DEFAULT_SETTINGS.upscale_hdr_enabled),)if (old_scale == "DLSS" and "scale_method" in old_enabled and("super_resolution" not in old_enabled or engine != "DLSS" or@@ -221,6 +230,8 @@ def import_settings_preset(old_order, old_enabled, video=True,scale_method=changes.get("nr_scale_method", DEFAULT_SETTINGS.nr_scale_method),upscale_engine=changes.get("upscale_engine", DEFAULT_SETTINGS.upscale_engine),+ upscale_vsr_enabled=changes.get("upscale_vsr_enabled", DEFAULT_SETTINGS.upscale_vsr_enabled),+ upscale_hdr_enabled=changes.get("upscale_hdr_enabled", DEFAULT_SETTINGS.upscale_hdr_enabled),)if changes.get("coloring_mode") == "Mode 2":changes["coloring_mode"] = "LUT"@@ -230,39 +241,43 @@ def import_settings_preset(if version < 15:for key in ("lut_resolution", *LUT_ADJUSTMENT_RANGES):changes[key] = getattr(DEFAULT_SETTINGS, key)- if version < 16:+ if version < 19:+ layout_defaults = DEFAULT_SETTINGS if version < 17 else currentfor mode, prefix in (("Image", "image"), ("Video", "video")):order_key = f"{prefix}_stage_order"enabled_key = f"{prefix}_enabled_stages"changes[order_key], changes[enabled_key] = migrate_stage_layout(- changes.get(order_key, getattr(DEFAULT_SETTINGS, order_key)),- changes.get(enabled_key, getattr(DEFAULT_SETTINGS, enabled_key)),+ changes.get(order_key, getattr(layout_defaults, order_key)),+ changes.get(enabled_key, getattr(layout_defaults, enabled_key)),video=mode == "Video",scale_method=changes.get("nr_scale_method", DEFAULT_SETTINGS.nr_scale_method),upscale_engine=changes.get("upscale_engine" if mode == "Video" else "upscale_image_engine",DEFAULT_SETTINGS.upscale_engine if mode == "Video" else DEFAULT_SETTINGS.upscale_image_engine,),+ upscale_vsr_enabled=changes.get("upscale_vsr_enabled", DEFAULT_SETTINGS.upscale_vsr_enabled),+ upscale_hdr_enabled=changes.get("upscale_hdr_enabled", DEFAULT_SETTINGS.upscale_hdr_enabled),)- for key in ("denoise_strength", "denoise_deblock", "denoise_temporal"):- changes[key] = getattr(DEFAULT_SETTINGS, key)if version < 17:- for mode, prefix in (("Image", "image"), ("Video", "video")):- order_key = f"{prefix}_stage_order"- enabled_key = f"{prefix}_enabled_stages"- changes[order_key], changes[enabled_key] = migrate_stage_layout(- changes.get(order_key, getattr(DEFAULT_SETTINGS, order_key)),- changes.get(enabled_key, getattr(DEFAULT_SETTINGS, enabled_key)),- video=mode == "Video",- scale_method=changes.get("nr_scale_method", DEFAULT_SETTINGS.nr_scale_method),- upscale_engine=changes.get(- "upscale_engine" if mode == "Video" else "upscale_image_engine",- DEFAULT_SETTINGS.upscale_engine if mode == "Video" else DEFAULT_SETTINGS.upscale_image_engine,- ),- )changes["cas_sharpness"] = DEFAULT_SETTINGS.cas_sharpnessif version < 18:changes["sharpening_method"] = DEFAULT_SETTINGS.sharpening_method+ if version < 20:+ changes["ffmpeg_device"] = DEFAULT_SETTINGS.ffmpeg_device+ if version < 21:+ changes["video_stage_order"], changes["video_enabled_stages"] = migrate_stage_layout(+ changes.get("video_stage_order", current.video_stage_order),+ changes.get("video_enabled_stages", current.video_enabled_stages),+ video=True,+ scale_method=changes.get("nr_scale_method", DEFAULT_SETTINGS.nr_scale_method),+ upscale_engine=changes.get("upscale_engine", DEFAULT_SETTINGS.upscale_engine),+ upscale_vsr_enabled=changes.get("upscale_vsr_enabled", DEFAULT_SETTINGS.upscale_vsr_enabled),+ upscale_hdr_enabled=changes.get("upscale_hdr_enabled", DEFAULT_SETTINGS.upscale_hdr_enabled),+ )+ if version < 22:+ changes["lut_reference_image"] = DEFAULT_SETTINGS.lut_reference_image+ if version < 27:+ changes["cache_codec"] = DEFAULT_SETTINGS.cache_codec# 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@@ -276,6 +291,17 @@ def import_settings_preset(if changes.get("upscale_vsr_quality") == 0:changes["upscale_vsr_quality"] = DEFAULT_SETTINGS.upscale_vsr_qualitymerged = replace(current, **changes)+ if version < 24:+ legacy_automatic = True if version < 23 else imported.get("automatic_container", True)+ if not isinstance(legacy_automatic, bool):+ raise ValueError("Preset setting 'automatic_container' must be a boolean.")+ if legacy_automatic:+ merged = replace(+ merged,+ container=container_for_codec(merged.codec),+ frame_interpolation_container=container_for_codec(merged.frame_interpolation_codec),+ upscale_container=container_for_codec(merged.upscale_codec),+ )return name, _validate(merged)diff --git a/src/settings/storage.py b/src/settings/storage.pyindex 2794728..7172f50 100644--- a/src/settings/storage.py+++ b/src/settings/storage.py@@ -8,8 +8,10 @@ import threadingfrom dataclasses import replacefrom pathlib import Path-from ..core.ffmpeg import HDR_ALLOWED_CODECS+from ..core.ffmpeg import HDR_ALLOWED_CODECS, container_for_codec, containers_for_codec+from ..core.ffmpeg.vulkan import valid_selectionfrom ..core.paths import CONFIG_PATH+from ..portable import decode_app_path, encode_app_pathfrom ..core.naming import RENAME_MODES, validate_renamefrom ..core.runtime import NR_STYLES, resolve_upscaling_modefrom ..core.dlss_modes import DLSS_METHODS, DLSS_MODES, DLSS_PRESETS@@ -18,11 +20,13 @@ from .migration import _migrate_codecfrom .models import (CODEC_CHOICES, CONFIG_SECTION, CONTAINER_CHOICES, DEFAULT_SETTINGS, IMAGE_FORMAT_CHOICES,IMAGE_16BIT_FORMATS, IMAGE_BIT_DEPTH_CHOICES,- PREVIEW_ENCODING_CHOICES, QUALITY_CHOICES, UPSCALE_MODE_CHOICES,+ QUALITY_CHOICES, UPSCALE_MODE_CHOICES,UPSCALE_PREVIEW_LENGTH_CHOICES, UISettings, _validate,IMAGE_STAGE_ORDER, VIDEO_STAGE_ORDER, IMAGE_SCALING_FILTERS, VIDEO_SCALING_FILTERS,LEGACY_IMAGE_STAGE_ORDER, LEGACY_VIDEO_STAGE_ORDER, COLORING_MODES, SHARPENING_METHODS,COLOR_MATCH_SOURCES, LUT_ADJUSTMENT_RANGES, LUT_RESOLUTIONS, migrate_stage_layout,+ CACHE_MEMORY_MODES,+ CACHE_VIDEO_CODECS,)from ..upscale.video.models import SETTING_FIELDS, options_from_settingsfrom ..upscale.image.models import SETTING_FIELDS as IMAGE_UPSCALE_FIELDS, options_from_settings as image_upscale_options@@ -166,6 +170,9 @@ def load_settings(path: str | os.PathLike[str]) -> UISettings:or DEFAULT_SETTINGS.ai_gpu_uuid,video_gpu_uuid=section.get("video_gpu_uuid", DEFAULT_SETTINGS.video_gpu_uuid).strip()or DEFAULT_SETTINGS.video_gpu_uuid,+ ffmpeg_device=section.get("ffmpeg_device", "auto") if valid_selection(section.get("ffmpeg_device", "auto")) else "auto",+ cache_memory_mode=choice("cache_memory_mode", CACHE_MEMORY_MODES, DEFAULT_SETTINGS.cache_memory_mode),+ cache_codec=choice("cache_codec", CACHE_VIDEO_CODECS, DEFAULT_SETTINGS.cache_codec),nr_style=choice("nr_style", tuple(NR_STYLES), DEFAULT_SETTINGS.nr_style),nr_intensity=number("nr_intensity", 0.0, 2.0, DEFAULT_SETTINGS.nr_intensity),nr_passes=integer("nr_passes", 1, 4, DEFAULT_SETTINGS.nr_passes),@@ -220,9 +227,6 @@ def load_settings(path: str | os.PathLike[str]) -> UISettings:image_format=image_format,image_quality=image_quality(),image_bit_depth=image_bit_depth,- denoise_strength=integer("denoise_strength", 0, 100, DEFAULT_SETTINGS.denoise_strength),- denoise_deblock=boolean("denoise_deblock", DEFAULT_SETTINGS.denoise_deblock),- denoise_temporal=integer("denoise_temporal", 0, 100, DEFAULT_SETTINGS.denoise_temporal),cas_sharpness=integer("cas_sharpness", 0, 100, DEFAULT_SETTINGS.cas_sharpness),sharpening_method=choice("sharpening_method", SHARPENING_METHODS,DEFAULT_SETTINGS.sharpening_method),@@ -230,8 +234,9 @@ def load_settings(path: str | os.PathLike[str]) -> UISettings:choice("coloring_mode", COLORING_MODES, DEFAULT_SETTINGS.coloring_mode)),color_match_source=choice("color_match_source", COLOR_MATCH_SOURCES,DEFAULT_SETTINGS.color_match_source),- color_match_reference=section.get("color_match_reference", "")[:4096],- lut_path=section.get("lut_path", "")[:4096],+ color_match_reference=decode_app_path(section.get("color_match_reference", ""))[:4096],+ lut_path=decode_app_path(section.get("lut_path", ""))[:4096],+ lut_reference_image=decode_app_path(section.get("lut_reference_image", ""))[:4096],lut_resolution=lut_resolution(),**{key: (number(key, *bounds, getattr(DEFAULT_SETTINGS, key)) if key == "lut_exposure"else integer(key, *bounds, getattr(DEFAULT_SETTINGS, key)))@@ -268,11 +273,6 @@ def load_settings(path: str | os.PathLike[str]) -> UISettings:),frame_interpolation_rename_mode=frame_interpolation_rename_mode,frame_interpolation_custom_suffix=frame_interpolation_custom_suffix,- preview_encoding=choice(- "preview_encoding",- PREVIEW_ENCODING_CHOICES,- DEFAULT_SETTINGS.preview_encoding,- ),upscale_mode=choice("upscale_mode",UPSCALE_MODE_CHOICES,@@ -336,10 +336,19 @@ def load_settings(path: str | os.PathLike[str]) -> UISettings:settings = replace(settings, frame_interpolation_hdr_mode=False)except Exception:pass- upscale_values = {}+ # Read codec/container together before validating the remaining upscale+ # fields; manual ProRes settings may change both from their defaults.+ upscale_codec = codec_choice("upscale_codec", DEFAULT_SETTINGS.upscale_codec)+ upscale_container = choice("upscale_container", CONTAINER_CHOICES, DEFAULT_SETTINGS.upscale_container)+ legacy_automatic_container = "automatic_container" in section and boolean("automatic_container", True)+ if legacy_automatic_container or upscale_container not in containers_for_codec(upscale_codec):+ upscale_container = container_for_codec(upscale_codec)+ upscale_values = {"upscale_codec": upscale_codec, "upscale_container": upscale_container}for prefix, names, factory in (("upscale_", SETTING_FIELDS, options_from_settings),("upscale_image_", IMAGE_UPSCALE_FIELDS, image_upscale_options)):for name in names:+ if prefix == "upscale_" and name in {"codec", "container"}:+ continuekey = prefix + namedefault = getattr(DEFAULT_SETTINGS, key)raw = section.get(key)@@ -362,6 +371,16 @@ def load_settings(path: str | os.PathLike[str]) -> UISettings:except (ValueError, TypeError, OverflowError):continuesettings = replace(settings, **upscale_values)+ # Preserve the effective selections from the retired automatic mode once.+ # Invalid combinations in an edited INI recover to a supported default.+ container_changes = {}+ for codec_key, container_key in (("codec", "container"),+ ("frame_interpolation_codec", "frame_interpolation_container"),+ ("upscale_codec", "upscale_container")):+ codec = getattr(settings, codec_key)+ if legacy_automatic_container or getattr(settings, container_key) not in containers_for_codec(codec):+ container_changes[container_key] = container_for_codec(codec)+ settings = replace(settings, **container_changes)def stage_values(order_key: str, enabled_key: str, default_order: tuple[str, ...], video: bool):try:@@ -372,7 +391,9 @@ def load_settings(path: str | os.PathLike[str]) -> UISettings:engine = settings.upscale_engine if video else settings.upscale_image_enginemigrated = migrate_stage_layout(order, enabled, video=video,scale_method=settings.nr_scale_method,- upscale_engine=engine)+ upscale_engine=engine,+ upscale_vsr_enabled=settings.upscale_vsr_enabled,+ upscale_hdr_enabled=settings.upscale_hdr_enabled)return migrated[0], migrated[1], (order, enabled) if legacy else Noneexcept (TypeError, ValueError, json.JSONDecodeError):return default_order, (), None@@ -415,15 +436,13 @@ def save_settings(path: str | os.PathLike[str], settings: UISettings) -> None:"video_stage_order": json.dumps(settings.video_stage_order),"image_enabled_stages": json.dumps(settings.image_enabled_stages),"video_enabled_stages": json.dumps(settings.video_enabled_stages),- "denoise_strength": str(settings.denoise_strength),- "denoise_deblock": str(settings.denoise_deblock).lower(),- "denoise_temporal": str(settings.denoise_temporal),"cas_sharpness": str(settings.cas_sharpness),"sharpening_method": settings.sharpening_method,"coloring_mode": settings.coloring_mode,"color_match_source": settings.color_match_source,- "color_match_reference": settings.color_match_reference.replace("%", "%%"),- "lut_path": settings.lut_path.replace("%", "%%"),+ "color_match_reference": encode_app_path(settings.color_match_reference).replace("%", "%%"),+ "lut_path": encode_app_path(settings.lut_path).replace("%", "%%"),+ "lut_reference_image": encode_app_path(settings.lut_reference_image).replace("%", "%%"),"lut_resolution": str(settings.lut_resolution),**{key: str(getattr(settings, key)) for key in LUT_ADJUSTMENT_RANGES},**{"upscale_image_" + name: str(getattr(settings, "upscale_image_" + name)) for name in IMAGE_UPSCALE_FIELDS},@@ -432,6 +451,9 @@ def save_settings(path: str | os.PathLike[str], settings: UISettings) -> None:"upscale_preview_length": settings.upscale_preview_length,"ai_gpu_uuid": settings.ai_gpu_uuid,"video_gpu_uuid": settings.video_gpu_uuid,+ "ffmpeg_device": settings.ffmpeg_device,+ "cache_memory_mode": settings.cache_memory_mode,+ "cache_codec": settings.cache_codec,"nr_style": settings.nr_style,"nr_intensity": f"{settings.nr_intensity:.2f}","nr_passes": str(settings.nr_passes),@@ -486,7 +508,6 @@ def save_settings(path: str | os.PathLike[str], settings: UISettings) -> None:"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,}temporary = config_path.with_name(f".{config_path.name}.tmp")@@ -512,11 +533,3 @@ def processing_gpu_settings() -> tuple[str, str]:with SETTINGS_STATE.lock:settings = SETTINGS_STATE.current or load_settings(CONFIG_PATH)return settings.ai_gpu_uuid, settings.video_gpu_uuid---def current_preview_encoding() -> str:- from ..core.ffmpeg.preview import normalize_preview_encoding-- with SETTINGS_STATE.lock:- settings = SETTINGS_STATE.current or load_settings(CONFIG_PATH)- return normalize_preview_encoding(settings.preview_encoding)diff --git a/src/upscale/video/cuda_pipeline.py b/src/upscale/video/cuda_pipeline.pyindex 91af397..d82473e 100644--- a/src/upscale/video/cuda_pipeline.py+++ b/src/upscale/video/cuda_pipeline.py@@ -1,712 +1,651 @@-from __future__ import annotations--"""Bounded NVDEC -> RTX Video CUDA -> same/cross-adapter NVENC pipeline."""--import gc-import math-import os-import queue-import shutil-import tempfile-import threading-import time-import uuid-from contextlib import suppress-from dataclasses import replace-from fractions import Fraction-from pathlib import Path-from typing import Any, Callable--import av-from av.codec.hwaccel import HWAccel--from ...core import app_log, ffmpeg-from ...core.disk_paths import OutputFile, prepare_output_dir-from ...core.gpu_detection import detect_gpus-from ...core.gpu_selection import resolve_ai_gpu-from ...core.jobs import Cancelled-from ...core.naming import output_filename, unique_output_path-from ...core.paths import JOBS-from .media import inspect_video, packed_bytes-from .models import UpscaleCapabilities, UpscaleOptions, UpscaleResult, output_size-from .native import RTXVideoSession, probe_capabilities-from .cuda_transfer import CudaTransferPool---class DLSSNeedsHostFallback(RuntimeError):- """The decoder could not expose a CUDA frame for this source."""---class _DLSSVideoAdapter:- def __init__(self, width, height, options, output_p010, controller, capabilities):- from ...core.dlss_bridge import DLSSSession- self.dlss = DLSSSession(width, height, options.dlss_mode, options.dlss_preset,- gpu_uuid=options.ai_gpu_uuid, even=True)- self.options = options- self.output_p010 = output_p010- self.hdr = None- self.closed = False- self.cuts = 0- if options.hdr_enabled:- self.hdr = RTXVideoSession(- self.dlss.output_width, self.dlss.output_height,- self.dlss.output_width, self.dlss.output_height,- replace(options, vsr_enabled=False),- 2 if output_p010 else 1, capabilities, controller)-- @property- def completed_frames(self):- return self.dlss.frames-- def process_cuda_frame(self, frame, *, color_matrix=1, color_range=0,- color_primaries=1, color_transfer=0, chroma_location=1,- rotation=0, output_p010=False):- intermediate, detail = self.dlss.process_cuda_frame(- frame, color_matrix=color_matrix, color_range=color_range,- rotation=rotation, phase=self.dlss.frames,- output_p010=output_p010)- self.cuts += int(detail["scene_cut"])- if self.hdr is None:- return intermediate, detail- intermediate.pts = getattr(frame, "pts", None)- if getattr(frame, "time_base", None) is not None:- intermediate.time_base = frame.time_base- else:- intermediate.time_base = Fraction(1, 1000)- intermediate.duration = getattr(frame, "duration", None)- try:- processed, hdr_detail = self.hdr.process_cuda_frame(- intermediate, color_matrix=color_matrix, color_range=color_range,- color_primaries=color_primaries, color_transfer=color_transfer,- chroma_location=chroma_location, output_p010=True)- finally:- del intermediate- return processed, {- "input_ms": float(detail["input_ms"]) + float(hdr_detail["input_ms"]),- "ngx_ms": float(detail["ngx_ms"]) + float(hdr_detail["ngx_ms"]),- "output_ms": float(detail["output_ms"]) + float(hdr_detail["output_ms"]),- }-- def structured_status(self, *, decode_backend, encode_backend):- result = self.dlss.last_result- status = {- "engine": "DLSS Super Resolution", "bridge_version": "DLSS ABI 1",- "mode": self.options.dlss_mode, "preset": self.options.dlss_preset,- "guide_estimated": True, "frames": self.dlss.frames,- "media_pipeline": "source-anchored DLSS", "synthetic_jitter": False,- "scene_cuts": self.cuts, "memory_path": "cuda_d3d12_shared",- "decode_backend": decode_backend, "encode_backend": encode_backend,- "render_width": result.render_width, "render_height": result.render_height,- "gpu_pre_resize": (result.render_width, result.render_height) != (- self.dlss.width, self.dlss.height),- }- if self.hdr is not None:- status["rtx_video_hdr"] = self.hdr.structured_status(- decode_backend="CUDA DLSS", encode_backend=encode_backend)- return status-- def close(self, abort=False):- if not self.closed:- if self.hdr is not None:- self.hdr.close(abort=abort)- self.dlss.close()- self.closed = True---_NVENC_CODEC = {- "H.264 (NVIDIA NVENC)": "h264_nvenc",- "H.265 (NVIDIA NVENC)": "hevc_nvenc",- "AV1 (NVIDIA NVENC)": "av1_nvenc",-}-_END = object()---def is_nvenc(codec: str) -> bool:- return ffmpeg._normalize_codec(codec) in _NVENC_CODEC---def _sdr_fallback(metadata: dict[str, Any]) -> str:- height = int(metadata["stream"]["height"])- return "bt470bg" if height == 576 else "smpte170m" if height <= 576 else "bt709"---def memory_route(codec: str, ai_gpu: dict[str, Any], video_gpu: dict[str, Any] | None) -> str:- """Return the observable pixel-memory route for an explicit codec/GPU choice."""- if not is_nvenc(codec):- return "gpu_to_pinned_host"- if video_gpu is None:- raise RuntimeError("An NVIDIA encoder was selected but no NVENC adapter is available.")- return ("cuda_zero_copy" if int(video_gpu["cuda_ordinal"]) == int(ai_gpu["cuda_ordinal"])- else "cuda_cross_gpu_peer_or_pinned")---def normalize_frame_timing(- *, frame_pts: int | None, frame_duration: int | None,- frame_time_base: Fraction | None, stream_time_base: Fraction,- origin_pts: int, delivered: int, default_duration: int,- last_pts: int | None,-) -> tuple[int, int, bool]:- """Normalize one CFR/VFR frame without dropping, duplicating, or re-timing it."""- frame_tb = frame_time_base or stream_time_base- fallback = frame_pts is None- pts = (delivered * default_duration if fallback else- round(Fraction(int(frame_pts)) * frame_tb / stream_time_base) - origin_pts)- if last_pts is not None and pts <= last_pts:- raise ValueError("Source timestamps are not strictly increasing; refusing to drop or duplicate frames.")- duration = max(- 1, round(Fraction(int(frame_duration or default_duration)) * frame_tb / stream_time_base))- return pts, duration, fallback---def _matrix_code(metadata: dict[str, Any]) -> int:- value = str(metadata["stream"].get("color_space") or "").casefold()- if value in {"", "unknown", "unspecified", "reserved"}:- pixel_format = str(metadata["stream"].get("pix_fmt") or "yuv420p")- value = "gbr" if av.VideoFormat(pixel_format).is_rgb else _sdr_fallback(metadata)- if value in {"bt2020nc", "bt2020c"}:- return 2- if value in {"bt470bg", "smpte170m", "smpte240m", "fcc"}:- return 0- return 1---def _primaries_code(metadata: dict[str, Any]) -> int:- value = str(metadata["stream"].get("color_primaries") or "").casefold()- if value in {"", "unknown", "unspecified", "reserved"}:- value = _sdr_fallback(metadata)- if value == "bt2020":- return 2- if value in {"bt470bg", "bt470m"}:- return 0- if value in {"smpte170m", "smpte240m", "smpte431", "smpte432"}:- return 3- return 1---def _transfer_code(metadata: dict[str, Any]) -> int:- value = str(metadata["stream"].get("color_transfer") or "").casefold()- if value in {"iec61966-2-1", "srgb"}:- return 1- if value in {"gamma22", "bt470m"}:- return 2- if value in {"gamma28", "bt470bg"}:- return 3- if value == "linear":- return 4- return 0---def _range_code(metadata: dict[str, Any]) -> int:- stream = metadata["stream"]- tagged_full = str(stream.get("color_range") or "").casefold() in {"pc", "jpeg", "full"}- pixel_format = str(stream.get("pix_fmt") or "yuv420p")- return int(tagged_full or av.VideoFormat(pixel_format).is_rgb)---def _chroma_location_code(metadata: dict[str, Any]) -> int:- return {"left": 0, "center": 1, "topleft": 2, "top": 3,- "bottomleft": 4, "bottom": 5}.get(- str(metadata["stream"].get("chroma_location") or "left").casefold(), 0)---def _set_color_properties(context: Any, hdr: bool) -> None:- context.color_primaries = 9 if hdr else 1- context.color_trc = 16 if hdr else 1- context.colorspace = 9 if hdr else 1- context.color_range = 1 # MPEG/limited range---class _SoftwareNormalizer:- """In-process fallback matching the prior color/rotation/SAR boundary."""-- def __init__(self, frame: Any, metadata: dict[str, Any], width: int, height: int, ten_bit: bool) -> None:- stream = metadata["stream"]- sd = int(stream["height"]) <= 576- fallback = "bt470bg" if int(stream["height"]) == 576 else "smpte170m" if sd else "bt709"- matrix = str(stream.get("color_space") or fallback)- primaries = str(stream.get("color_primaries") or fallback)- transfer = str(stream.get("color_transfer") or "bt709")- color_range = "pc" if _range_code(metadata) else "tv"- precision = "yuv444p10le" if ten_bit else "yuv444p"- final_format = "gbrp10le" if ten_bit else "rgba"- graph = av.filter.Graph()- source = graph.add_buffer(template=frame)- if av.VideoFormat(str(stream.get("pix_fmt") or "yuv420p")).is_rgb:- # Lossless FFV1 intermediates in the ordered workflow are RGB.- # FFmpeg's colorspace filter does not accept ispace=gbr. Preserve- # the RGB pixels and depth directly at this stage boundary.- colors = graph.add("format", "gbrp10le" if ten_bit else "gbrp")- else:- colors = graph.add(- "colorspace",- f"ispace={matrix}:iprimaries={primaries}:itrc={transfer}:irange={color_range}:"- f"all=bt709:trc=gamma22:range=pc:format={precision}",- )- source.link_to(colors)- node = colors- rotation = int(metadata["rotation"])- if rotation == 90:- rotated = graph.add("transpose", "cclock")- node.link_to(rotated); node = rotated- elif rotation == 270:- rotated = graph.add("transpose", "clock")- node.link_to(rotated); node = rotated- elif rotation == 180:- horizontal, vertical = graph.add("hflip"), graph.add("vflip")- node.link_to(horizontal); horizontal.link_to(vertical); node = vertical- scaled = graph.add("scale", f"{width}:{height}:flags=lanczos")- square = graph.add("setsar", "1")- formatted = graph.add("format", final_format)- sink = graph.add("buffersink")- node.link_to(scaled); scaled.link_to(square); square.link_to(formatted); formatted.link_to(sink)- graph.configure()- self.graph, self.source, self.sink = graph, source, sink-- def convert(self, frame: Any):- self.source.push(frame)- return packed_bytes(self.sink.pull())---def _put_bounded(target: queue.Queue, item: Any, stop: threading.Event,- controller: Any, failures: list[BaseException]) -> bool:- while not stop.is_set():- if controller.cancel.is_set():- stop.set()- return False- if failures:- stop.set()- return False- try:- target.put(item, timeout=0.05)- return True- except queue.Full:- continue- return False---def _get_bounded(source: queue.Queue, stop: threading.Event, controller: Any,- failures: list[BaseException]) -> Any:- while True:- if controller.cancel.is_set():- stop.set()- raise Cancelled("Upscale stopped by user.")- if failures:- stop.set()- raise failures[0]- try:- return source.get(timeout=0.05)- except queue.Empty:- if stop.is_set():- if failures:- raise failures[0]- return _END---def convert_video_cuda_nvenc(- source: Path,- options: UpscaleOptions,- *,- controller: Any,- progress: Callable[[float, str], None] | None,- output_dir: str | os.PathLike[str] | None,- metadata: dict[str, Any] | None = None,- capabilities: UpscaleCapabilities | None = None,- video_gpu: dict[str, Any] | None = None,-) -> UpscaleResult:- """Run the production CUDA route, including explicit cross-GPU NVENC."""- started = time.perf_counter()- report_path = app_log.session_path()- metadata = metadata or inspect_video(source, controller, reject_hdr=True)- width, height = int(metadata["width"]), int(metadata["height"])- output_width, output_height, _ = output_size(width, height, options)- gpus = detect_gpus()- ai_gpu = capabilities.gpu if capabilities is not None else resolve_ai_gpu(gpus, options.ai_gpu_uuid)- ai_ordinal = int(ai_gpu["cuda_ordinal"])- requested_video_uuid = str(ai_gpu["uuid"]) if options.video_gpu_uuid == "auto" else options.video_gpu_uuid- video_gpu = video_gpu or ffmpeg.resolve_video_gpu(- gpus, requested_video_uuid, options.codec, output_width, output_height)- if video_gpu is None:- raise RuntimeError("The CUDA RTX Video route requires an available NVENC adapter.")- encode_ordinal = int(video_gpu["cuda_ordinal"])- codec_name = _NVENC_CODEC[ffmpeg._normalize_codec(options.codec)]- input_format = 2 if int(metadata["depth"]) > 8 else 1- output_p010 = bool(options.hdr_enabled or (input_format == 2 and ffmpeg.hdr_mode_supported(options.codec)))- quality = ffmpeg.resolve_encoding_quality(- options.quality, options.codec, output_width, output_height,- float(metadata["rate"]), hdr_mode=output_p010,- )- preview = options.preview_frames is not None or options.preview_seconds is not None- stamp = time.strftime("%Y%m%d-%H%M%S") + "-" + uuid.uuid4().hex[:8]- extension = {"MP4": ".mp4", "MKV": ".mkv", "MOV": ".mov"}[options.container]- destination = prepare_output_dir(output_dir)- kind = ("DLSS_PREVIEW" if preview else "DLSS") if options.engine == "DLSS" else (- "RTXVIDEO_PREVIEW" if preview else "RTXVIDEO")- output = unique_output_path(destination / output_filename(- source, extension, "Auto" if preview else options.rename_mode,- options.custom_suffix, f"{source.stem}_{kind}_{stamp}",- ))- destination_file = OutputFile(output)- JOBS.mkdir(exist_ok=True)- session: RTXVideoSession | _DLSSVideoAdapter | None = None- decoded_container: Any | None = None- encoded_container: Any | None = None- delivered = 0- decode_backends: set[str] = set()- timings = {- "decode_seconds": 0.0, "software_prepare_seconds": 0.0,- "bridge_input_seconds": 0.0, "ngx_seconds": 0.0,- "bridge_output_seconds": 0.0, "encode_seconds": 0.0,- }- failures: list[BaseException] = []- stop = threading.Event()- decode_stop = threading.Event()- decode_thread: threading.Thread | None = None- encode_thread: threading.Thread | None = None- transfer_pool: CudaTransferPool | None = None-- def update(value: float, message: str) -> None:- if controller.cancel.is_set():- raise Cancelled("Upscale stopped by user.")- if progress:- progress(max(0.0, min(1.0, value)), message)-- try:- update(0.01, "Preparing video processing")- job = tempfile.TemporaryDirectory(prefix="rtx-video-cuda-", dir=JOBS)- try:- job_dir = Path(job.name)- temp_video = job_dir / {"MP4": "encoded.mp4", "MKV": "encoded.mkv", "MOV": "encoded.mov"}[options.container]- decode_device = HWAccel(- "cuda", device=str(ai_ordinal), allow_software_fallback=True,- options={"primary_ctx": "1"}, is_hw_owned=True,- )- encode_device = HWAccel(- "cuda", device=str(encode_ordinal), options={"primary_ctx": "1"}, is_hw_owned=True,- )- decoded_container = av.open(str(source), hwaccel=decode_device)- input_stream = decoded_container.streams.video[0]- input_stream.thread_type = "AUTO"- decoder = iter(decoded_container.decode(input_stream))- decode_start = time.perf_counter()- try:- first_frame = next(decoder)- except StopIteration as exc:- raise ValueError("The input contains no decodable video frames.") from exc- timings["decode_seconds"] += time.perf_counter() - decode_start- if options.engine == "DLSS" and first_frame.format.name != "cuda":- raise DLSSNeedsHostFallback("NVDEC did not expose a CUDA frame.")-- encoded_container = av.open(str(temp_video), mode="w")- output_stream = encoded_container.add_stream(codec_name, rate=metadata["rate"], hwaccel=encode_device)- output_stream.width, output_stream.height = output_width, output_height- output_stream.pix_fmt = "cuda"- output_stream.codec_context.sw_format = "p010le" if output_p010 else "nv12"- output_stream.time_base = input_stream.time_base- output_stream.codec_context.time_base = input_stream.time_base- encoder_options = {- "preset": "p6", "rc": "vbr", "gpu": str(encode_ordinal),- # Keep the production encoder's normal B-frame structure. Bound- # submission/output buffering to the bridge's eight externally- # owned surfaces without changing p6/HQ/rate-control decisions.- "rc-lookahead": "0", "surfaces": "8", "delay": "3",- }- if codec_name != "av1_nvenc":- encoder_options["tune"] = "hq"- if quality["mode"] == "constant-quality":- encoder_options["cq"] = "0"- output_stream.codec_context.bit_rate = 0- else:- output_stream.codec_context.bit_rate = int(quality["target_bitrate_kbps"]) * 1000- output_stream.codec_context.options = encoder_options- _set_color_properties(output_stream.codec_context, bool(options.hdr_enabled))- # Force decoder and encoder CUDA contexts to exist before NGX.- output_stream.codec_context.open()- if options.engine == "DLSS":- capabilities = (capabilities or probe_capabilities(- options.ai_gpu_uuid, controller=controller)) if options.hdr_enabled else None- session = _DLSSVideoAdapter(- width, height, options, output_p010, controller, capabilities)- else:- capabilities = capabilities or probe_capabilities(options.ai_gpu_uuid, controller=controller)- session = RTXVideoSession(- width, height, output_width, output_height, options, input_format,- capabilities, controller)- if encode_ordinal != ai_ordinal:- transfer_pool = CudaTransferPool(ai_ordinal, encode_ordinal, controller)-- decode_queue: queue.Queue = queue.Queue(maxsize=4)- encode_queue: queue.Queue = queue.Queue(maxsize=4)-- def decode_worker() -> None:- def put_decode(item: Any) -> bool:- while not stop.is_set() and not decode_stop.is_set():- if controller.cancel.is_set() or failures:- stop.set()- return False- try:- decode_queue.put(item, timeout=0.05)- return True- except queue.Full:- continue- return False-- try:- if not put_decode(first_frame):- return- while not stop.is_set() and not decode_stop.is_set():- tick = time.perf_counter()- try:- frame = next(decoder)- except StopIteration:- timings["decode_seconds"] += time.perf_counter() - tick- break- timings["decode_seconds"] += time.perf_counter() - tick- if frame.is_corrupt:- raise RuntimeError("The video decoder returned a corrupt frame.")- if not put_decode(frame):- return- except BaseException as exc:- failures.append(exc); stop.set()- finally:- if not decode_stop.is_set():- put_decode(_END)-- encoded_frames = [0]-- def encode_worker() -> None:- try:- while not stop.is_set():- item = _get_bounded(encode_queue, stop, controller, failures)- if item is _END:- break- tick = time.perf_counter()- for packet in output_stream.encode(item):- encoded_container.mux(packet)- timings["encode_seconds"] += time.perf_counter() - tick- encoded_frames[0] += 1- del item- if not failures and not controller.cancel.is_set():- tick = time.perf_counter()- for packet in output_stream.encode():- encoded_container.mux(packet)- timings["encode_seconds"] += time.perf_counter() - tick- except BaseException as exc:- failures.append(exc); stop.set()-- decode_thread = threading.Thread(target=decode_worker, name="rtx-video-decoder", daemon=True)- encode_thread = threading.Thread(target=encode_worker, name="rtx-video-encoder", daemon=True)- pipeline_started = time.perf_counter()- decode_thread.start(); encode_thread.start()-- stream_tb = input_stream.time_base or Fraction(1, max(1, round(float(metadata["rate"]))))- default_duration = max(1, round(Fraction(1, 1) / metadata["rate"] / stream_tb))- origin_pts = round(Fraction(str(metadata["origin"])) / stream_tb)- first_time: Fraction | None = None- preview_pts_origin: int | None = None- last_pts: int | None = None- stopped_early = False- timestamp_fallbacks = 0- software_normalizer: _SoftwareNormalizer | None = None- estimated = int(metadata["frames"] or max(1, math.ceil(metadata["duration"] * float(metadata["rate"]))))- if options.preview_frames is not None:- estimated = min(estimated, int(options.preview_frames))- elif options.preview_seconds is not None:- estimated = min(estimated, max(1, math.ceil(options.preview_seconds * float(metadata["rate"]))))- last_update = 0.0- while True:- frame = _get_bounded(decode_queue, stop, controller, failures)- if frame is _END:- break- pts, duration, used_fallback = normalize_frame_timing(- frame_pts=frame.pts, frame_duration=frame.duration,- frame_time_base=frame.time_base, stream_time_base=stream_tb,- origin_pts=origin_pts, delivered=delivered,- default_duration=default_duration, last_pts=last_pts,- )- frame_tb = frame.time_base or stream_tb- timestamp_fallbacks += int(used_fallback)- timestamp = Fraction(pts) * stream_tb- if first_time is None:- first_time = timestamp- if ((options.preview_frames is not None and delivered >= int(options.preview_frames)) or- (options.preview_seconds is not None and delivered and- float(timestamp - first_time) >= float(options.preview_seconds))):- stopped_early = True- decode_stop.set()- del frame- break- if frame.format.name == "cuda":- decode_backends.add("nvdec")- processed, detail = session.process_cuda_frame(- frame, color_matrix=_matrix_code(metadata), color_range=_range_code(metadata),- color_primaries=_primaries_code(metadata), color_transfer=_transfer_code(metadata),- chroma_location=_chroma_location_code(metadata),- rotation=int(metadata["rotation"]), output_p010=output_p010,- )- else:- if options.engine == "DLSS":- raise RuntimeError("DLSS CUDA decoding changed to software mid-stream.")- decode_backends.add("software")- tick = time.perf_counter()- if software_normalizer is None:- software_normalizer = _SoftwareNormalizer(frame, metadata, width, height, input_format == 2)- packed = software_normalizer.convert(frame)- timings["software_prepare_seconds"] += time.perf_counter() - tick- processed, detail = session.process_host_to_cuda_frame(- packed, output_p010=output_p010, pts=pts,- time_base=stream_tb, duration=duration,- )- if transfer_pool is not None:- transferred, transfer_detail = transfer_pool.transfer(processed)- del processed- processed = transferred- timings["cross_gpu_seconds"] = (- timings.get("cross_gpu_seconds", 0.0) +- float(transfer_detail["copy_ms"]) / 1000.0- )- timings["bridge_input_seconds"] += detail["input_ms"] / 1000.0- timings["ngx_seconds"] += detail["ngx_ms"] / 1000.0- timings["bridge_output_seconds"] += detail["output_ms"] / 1000.0- if preview:- if preview_pts_origin is None:- preview_pts_origin = pts- processed.pts = pts - preview_pts_origin- else:- processed.pts = pts- processed.time_base = stream_tb- processed.duration = duration- if not _put_bounded(encode_queue, processed, stop, controller, failures):- raise failures[0] if failures else Cancelled("Upscale stopped by user.")- delivered += 1- last_pts = pts- del frame, processed- now = time.perf_counter()- if now - last_update > 0.2:- update(- min(0.87, 0.05 + 0.82 * delivered / max(1, estimated)),- "Upscaling video",- )- last_update = now- if not delivered:- raise ValueError("The input contains no decodable video frames.")- _put_bounded(encode_queue, _END, threading.Event(), controller, failures)- decode_thread.join(timeout=30)- encode_thread.join(timeout=180)- if decode_thread.is_alive() or encode_thread.is_alive():- raise RuntimeError("The bounded RTX Video pipeline did not drain cleanly.")- timings["pipeline_seconds"] = time.perf_counter() - pipeline_started- if failures:- raise failures[0]- if encoded_frames[0] != delivered:- raise RuntimeError(f"NVENC accepted {encoded_frames[0]} frames instead of {delivered}.")- encoded_container.close(); encoded_container = None- decoded_container.close(); decoded_container = None- gc.collect()- transfer_diagnostics = transfer_pool.diagnostics() if transfer_pool is not None else {}- if transfer_pool is not None:- transfer_pool.close()- transfer_pool = None- session_status = session.structured_status(- decode_backend="+".join(sorted(decode_backends)) or "unknown",- encode_backend=codec_name,- )- session.close()- if session.completed_frames != delivered:- raise RuntimeError("GPU bridge completion does not match frame accounting.")- gc.collect()-- if not preview and (not metadata["frames"] or delivered != metadata["frames"]):- exact = ffmpeg.probe_video(source, count_mode="exact", strict_decode=True, controller=controller)- if int(exact["frames"]) != delivered:- raise RuntimeError(f"Source has {exact['frames']} frames but only {delivered} were processed.")- update(0.90, "Muxing original audio, subtitles, chapters, and metadata")- mux_started = time.perf_counter()- audio_diagnostics: dict = {}- ffmpeg.final_mux(- temp_video, source, destination_file.temporary, options.container, controller,- preserve_supported_subtitles=True, source_time_origin=metadata["origin"],- audio_diagnostics=audio_diagnostics,- )- timings["final_mux_seconds"] = time.perf_counter() - mux_started- update(0.96, "Verifying output frames, resolution, and HDR signaling")- verified = ffmpeg.probe_video(destination_file.temporary, count_mode="packets", controller=controller)- if int(verified["frames"]) != delivered:- verified = ffmpeg.probe_video(- destination_file.temporary, count_mode="exact", strict_decode=True, controller=controller)- if int(verified["frames"]) != delivered or (int(verified["width"]), int(verified["height"])) != (output_width, output_height):- raise RuntimeError("Saved output does not match processed frame count or dimensions.")- saved = inspect_video(destination_file.temporary, controller)- if options.hdr_enabled and (- saved["depth"] < 10 or not saved["hdr"] or- saved["stream"].get("color_primaries") != "bt2020" or- saved["stream"].get("color_space") != "bt2020nc"- ):- raise RuntimeError("Saved file failed HDR color and bit-depth verification.")- if not options.hdr_enabled and saved["hdr"]:- raise RuntimeError("SDR output unexpectedly contains HDR signaling.")- if controller.cancel.is_set():- raise Cancelled("Upscale stopped by user.")- elapsed = time.perf_counter() - started- stage_per_frame = {- "decode_ms": timings["decode_seconds"] * 1000 / delivered,- "bridge_ms": (timings["bridge_input_seconds"] + timings["ngx_seconds"] + timings["bridge_output_seconds"]) * 1000 / delivered,- "encode_ms": timings["encode_seconds"] * 1000 / delivered,- }- slowest_ms = max(stage_per_frame.values())- ceiling_fps = 1000.0 / slowest_ms if slowest_ms > 0 else 0.0- throughput = delivered / max(timings["pipeline_seconds"], 1e-9)- timings.update(- steady_state_fps=throughput, slowest_stage_ceiling_fps=ceiling_fps,- ceiling_utilization=throughput / ceiling_fps if ceiling_fps else 0.0,- timestamp_fallbacks=timestamp_fallbacks,- )- session_status["timings"] = dict(timings)- session_status["adapters"] = {"ai": ai_gpu, "decode": ai_gpu, "encode": video_gpu}- session_status["audio_streams"] = audio_diagnostics.get("streams", [])- if transfer_diagnostics:- session_status["cross_gpu_transfer"] = transfer_diagnostics- session_status["memory_path"] = transfer_diagnostics["memory_path"]- session_status["upload_bytes"] = (- int(session_status.get("upload_bytes", 0)) +- int(transfer_diagnostics["pinned_upload_bytes"])- )- session_status["download_bytes"] = (- int(session_status.get("download_bytes", 0)) +- int(transfer_diagnostics["pinned_download_bytes"])- )- destination_file.publish()- app_log.info(- "upscale-cuda", f"done src={source.name} out={output.name} frames={delivered} "- f"elapsed={elapsed:.2f}s fps={delivered / max(elapsed, 1e-9):.1f} memory={session_status['memory_path']}",- )- update(1.0, "Complete — CUDA-resident RTX Video confirmed")- return UpscaleResult(- str(output), report_path, delivered, output_width, output_height,- options.hdr_enabled, elapsed,- bridge_version=("DLSS ABI 1" if options.engine == "DLSS" else str(capabilities.bridge_version)),- memory_path=str(session_status["memory_path"]),- decode_backend=str(session_status["decode_backend"]),- encode_backend=codec_name, timings=timings, bridge_status=session_status,- )- finally:- job.cleanup()- except BaseException:- stop.set()- decode_stop.set()- for thread in (decode_thread, encode_thread):- if thread is not None:- thread.join(timeout=2)- if session is not None and not session.closed:- with suppress(Exception):- session.close(abort=True)- if transfer_pool is not None and not transfer_pool.closed:- with suppress(Exception):- transfer_pool.close(abort=True)- if encoded_container is not None:- with suppress(Exception):- encoded_container.close()- if decoded_container is not None:- with suppress(Exception):- decoded_container.close()- destination_file.cleanup(rollback=True)- raise+from __future__ import annotations++"""Bounded NVDEC -> RTX Video CUDA -> same/cross-adapter NVENC pipeline."""++import gc+import math+import os+import queue+import shutil+import tempfile+import threading+import time+import uuid+from contextlib import suppress+from dataclasses import replace+from fractions import Fraction+from pathlib import Path+from typing import Any, Callable++import av+from av.codec.hwaccel import HWAccel++from ...core import app_log, ffmpeg+from ...core.disk_paths import OutputFile, prepare_output_dir+from ...core.gpu_detection import detect_gpus+from ...core.gpu_selection import resolve_ai_gpu+from ...core.jobs import Cancelled+from ...core.naming import output_filename, unique_output_path+from ...core.paths import JOBS+from .media import inspect_video, packed_bytes+from .models import UpscaleCapabilities, UpscaleOptions, UpscaleResult, output_size+from .native import RTXVideoSession, probe_capabilities+from .cuda_transfer import CudaTransferPool+++class DLSSNeedsHostFallback(RuntimeError):+ """The decoder could not expose a CUDA frame for this source."""+++class _DLSSVideoAdapter:+ def __init__(self, width, height, options, output_p010, controller, capabilities):+ from ...core.dlss_bridge import DLSSSession+ self.dlss = DLSSSession(width, height, options.dlss_mode, options.dlss_preset,+ gpu_uuid=options.ai_gpu_uuid, even=True)+ self.options = options+ self.output_p010 = output_p010+ self.hdr = None+ self.closed = False+ self.cuts = 0+ if options.hdr_enabled:+ self.hdr = RTXVideoSession(+ self.dlss.output_width, self.dlss.output_height,+ self.dlss.output_width, self.dlss.output_height,+ replace(options, vsr_enabled=False),+ 2 if output_p010 else 1, capabilities, controller)++ @property+ def completed_frames(self):+ return self.dlss.frames++ def process_cuda_frame(self, frame, *, color_matrix=1, color_range=0,+ color_primaries=1, color_transfer=0, chroma_location=1,+ rotation=0, output_p010=False):+ intermediate, detail = self.dlss.process_cuda_frame(+ frame, color_matrix=color_matrix, color_range=color_range,+ rotation=rotation, phase=self.dlss.frames,+ output_p010=output_p010)+ self.cuts += int(detail["scene_cut"])+ if self.hdr is None:+ return intermediate, detail+ intermediate.pts = getattr(frame, "pts", None)+ if getattr(frame, "time_base", None) is not None:+ intermediate.time_base = frame.time_base+ else:+ intermediate.time_base = Fraction(1, 1000)+ intermediate.duration = getattr(frame, "duration", None)+ try:+ processed, hdr_detail = self.hdr.process_cuda_frame(+ intermediate, color_matrix=color_matrix, color_range=color_range,+ color_primaries=color_primaries, color_transfer=color_transfer,+ chroma_location=chroma_location, output_p010=True)+ finally:+ del intermediate+ return processed, {+ "input_ms": float(detail["input_ms"]) + float(hdr_detail["input_ms"]),+ "ngx_ms": float(detail["ngx_ms"]) + float(hdr_detail["ngx_ms"]),+ "output_ms": float(detail["output_ms"]) + float(hdr_detail["output_ms"]),+ }++ def structured_status(self, *, decode_backend, encode_backend):+ result = self.dlss.last_result+ status = {+ "engine": "DLSS Super Resolution", "bridge_version": "DLSS ABI 1",+ "mode": self.options.dlss_mode, "preset": self.options.dlss_preset,+ "guide_estimated": True, "frames": self.dlss.frames,+ "media_pipeline": "source-anchored DLSS", "synthetic_jitter": False,+ "scene_cuts": self.cuts, "memory_path": "cuda_d3d12_shared",+ "decode_backend": decode_backend, "encode_backend": encode_backend,+ "render_width": result.render_width, "render_height": result.render_height,+ "gpu_pre_resize": (result.render_width, result.render_height) != (+ self.dlss.width, self.dlss.height),+ }+ if self.hdr is not None:+ status["rtx_video_hdr"] = self.hdr.structured_status(+ decode_backend="CUDA DLSS", encode_backend=encode_backend)+ return status++ def close(self, abort=False):+ if not self.closed:+ if self.hdr is not None:+ self.hdr.close(abort=abort)+ self.dlss.close()+ self.closed = True+++_NVENC_CODEC = {+ "H.264 (NVIDIA NVENC)": "h264_nvenc",+ "H.265 (NVIDIA NVENC)": "hevc_nvenc",+ "AV1 (NVIDIA NVENC)": "av1_nvenc",+}+_END = object()+++def is_nvenc(codec: str) -> bool:+ return ffmpeg._normalize_codec(codec) in _NVENC_CODEC+++def _sdr_fallback(metadata: dict[str, Any]) -> str:+ height = int(metadata["stream"]["height"])+ return "bt470bg" if height == 576 else "smpte170m" if height <= 576 else "bt709"+++def memory_route(codec: str, ai_gpu: dict[str, Any], video_gpu: dict[str, Any] | None) -> str:+ """Return the observable pixel-memory route for an explicit codec/GPU choice."""+ if not is_nvenc(codec):+ return "gpu_to_pinned_host"+ if video_gpu is None:+ raise RuntimeError("An NVIDIA encoder was selected but no NVENC adapter is available.")+ return ("cuda_zero_copy" if int(video_gpu["cuda_ordinal"]) == int(ai_gpu["cuda_ordinal"])+ else "cuda_cross_gpu_peer_or_pinned")+++def normalize_frame_timing(+ *, frame_pts: int | None, frame_duration: int | None,+ frame_time_base: Fraction | None, stream_time_base: Fraction,+ origin_pts: int, delivered: int, default_duration: int,+ last_pts: int | None,+) -> tuple[int, int, bool]:+ """Normalize one CFR/VFR frame without dropping, duplicating, or re-timing it."""+ frame_tb = frame_time_base or stream_time_base+ fallback = frame_pts is None+ pts = (delivered * default_duration if fallback else+ round(Fraction(int(frame_pts)) * frame_tb / stream_time_base) - origin_pts)+ if last_pts is not None and pts <= last_pts:+ raise ValueError("Source timestamps are not strictly increasing; refusing to drop or duplicate frames.")+ duration = max(+ 1, round(Fraction(int(frame_duration or default_duration)) * frame_tb / stream_time_base))+ return pts, duration, fallback+++def _matrix_code(metadata: dict[str, Any]) -> int:+ value = str(metadata["stream"].get("color_space") or "").casefold()+ if value in {"", "unknown", "unspecified", "reserved"}:+ pixel_format = str(metadata["stream"].get("pix_fmt") or "yuv420p")+ value = "gbr" if av.VideoFormat(pixel_format).is_rgb else _sdr_fallback(metadata)+ if value in {"bt2020nc", "bt2020c"}:+ return 2+ if value in {"bt470bg", "smpte170m", "smpte240m", "fcc"}:+ return 0+ return 1+++def _primaries_code(metadata: dict[str, Any]) -> int:+ value = str(metadata["stream"].get("color_primaries") or "").casefold()+ if value in {"", "unknown", "unspecified", "reserved"}:+ value = _sdr_fallback(metadata)+ if value == "bt2020":+ return 2+ if value in {"bt470bg", "bt470m"}:+ return 0+ if value in {"smpte170m", "smpte240m", "smpte431", "smpte432"}:+ return 3+ return 1+++def _transfer_code(metadata: dict[str, Any]) -> int:+ value = str(metadata["stream"].get("color_transfer") or "").casefold()+ if value in {"iec61966-2-1", "srgb"}:+ return 1+ if value in {"gamma22", "bt470m"}:+ return 2+ if value in {"gamma28", "bt470bg"}:+ return 3+ if value == "linear":+ return 4+ return 0+++def _range_code(metadata: dict[str, Any]) -> int:+ stream = metadata["stream"]+ tagged_full = str(stream.get("color_range") or "").casefold() in {"pc", "jpeg", "full"}+ pixel_format = str(stream.get("pix_fmt") or "yuv420p")+ return int(tagged_full or av.VideoFormat(pixel_format).is_rgb)+++def _chroma_location_code(metadata: dict[str, Any]) -> int:+ return {"left": 0, "center": 1, "topleft": 2, "top": 3,+ "bottomleft": 4, "bottom": 5}.get(+ str(metadata["stream"].get("chroma_location") or "left").casefold(), 0)+++def _set_color_properties(context: Any, hdr: bool) -> None:+ context.color_primaries = 9 if hdr else 1+ context.color_trc = 16 if hdr else 1+ context.colorspace = 9 if hdr else 1+ context.color_range = 1 # MPEG/limited range+++def _put_bounded(target: queue.Queue, item: Any, stop: threading.Event,+ controller: Any, failures: list[BaseException]) -> bool:+ while not stop.is_set():+ if controller.cancel.is_set():+ stop.set()+ return False+ if failures:+ stop.set()+ return False+ try:+ target.put(item, timeout=0.05)+ return True+ except queue.Full:+ continue+ return False+++def _get_bounded(source: queue.Queue, stop: threading.Event, controller: Any,+ failures: list[BaseException]) -> Any:+ while True:+ if controller.cancel.is_set():+ stop.set()+ raise Cancelled("Upscale stopped by user.")+ if failures:+ stop.set()+ raise failures[0]+ try:+ return source.get(timeout=0.05)+ except queue.Empty:+ if stop.is_set():+ if failures:+ raise failures[0]+ return _END+++def convert_video_cuda_nvenc(+ source: Path,+ options: UpscaleOptions,+ *,+ controller: Any,+ progress: Callable[[float, str], None] | None,+ output_dir: str | os.PathLike[str] | None,+ metadata: dict[str, Any] | None = None,+ capabilities: UpscaleCapabilities | None = None,+ video_gpu: dict[str, Any] | None = None,+) -> UpscaleResult:+ """Run the production CUDA route, including explicit cross-GPU NVENC."""+ started = time.perf_counter()+ report_path = app_log.session_path()+ metadata = metadata or inspect_video(source, controller, reject_hdr=True)+ width, height = int(metadata["width"]), int(metadata["height"])+ output_width, output_height, _ = output_size(width, height, options)+ gpus = detect_gpus()+ ai_gpu = capabilities.gpu if capabilities is not None else resolve_ai_gpu(gpus, options.ai_gpu_uuid)+ ai_ordinal = int(ai_gpu["cuda_ordinal"])+ requested_video_uuid = str(ai_gpu["uuid"]) if options.video_gpu_uuid == "auto" else options.video_gpu_uuid+ video_gpu = video_gpu or ffmpeg.resolve_video_gpu(+ gpus, requested_video_uuid, options.codec, output_width, output_height)+ if video_gpu is None:+ raise RuntimeError("The CUDA RTX Video route requires an available NVENC adapter.")+ encode_ordinal = int(video_gpu["cuda_ordinal"])+ codec_name = _NVENC_CODEC[ffmpeg._normalize_codec(options.codec)]+ input_format = 2 if int(metadata["depth"]) > 8 else 1+ output_p010 = bool(options.hdr_enabled or (input_format == 2 and ffmpeg.hdr_mode_supported(options.codec)))+ quality = ffmpeg.resolve_encoding_quality(+ options.quality, options.codec, output_width, output_height,+ float(metadata["rate"]), hdr_mode=output_p010,+ )+ preview = options.preview_frames is not None or options.preview_seconds is not None+ stamp = time.strftime("%Y%m%d-%H%M%S") + "-" + uuid.uuid4().hex[:8]+ extension = {"MP4": ".mp4", "MKV": ".mkv", "MOV": ".mov"}[options.container]+ destination = prepare_output_dir(output_dir)+ kind = ("DLSS_PREVIEW" if preview else "DLSS") if options.engine == "DLSS" else (+ "RTXVIDEO_PREVIEW" if preview else "RTXVIDEO")+ output = unique_output_path(destination / output_filename(+ source, extension, "Auto" if preview else options.rename_mode,+ options.custom_suffix, f"{source.stem}_{kind}_{stamp}",+ ))+ destination_file = OutputFile(output)+ JOBS.mkdir(exist_ok=True)+ session: RTXVideoSession | _DLSSVideoAdapter | None = None+ decoded_container: Any | None = None+ encoded_container: Any | None = None+ delivered = 0+ decode_backends: set[str] = set()+ timings = {+ "decode_seconds": 0.0, "software_prepare_seconds": 0.0,+ "bridge_input_seconds": 0.0, "ngx_seconds": 0.0,+ "bridge_output_seconds": 0.0, "encode_seconds": 0.0,+ }+ failures: list[BaseException] = []+ stop = threading.Event()+ decode_stop = threading.Event()+ decode_thread: threading.Thread | None = None+ encode_thread: threading.Thread | None = None+ transfer_pool: CudaTransferPool | None = None++ def update(value: float, message: str) -> None:+ if controller.cancel.is_set():+ raise Cancelled("Upscale stopped by user.")+ if progress:+ progress(max(0.0, min(1.0, value)), message)++ try:+ update(0.01, "Preparing video processing")+ job = tempfile.TemporaryDirectory(prefix="rtx-video-cuda-", dir=JOBS)+ try:+ job_dir = Path(job.name)+ temp_video = job_dir / {"MP4": "encoded.mp4", "MKV": "encoded.mkv", "MOV": "encoded.mov"}[options.container]+ decode_device = HWAccel(+ "cuda", device=str(ai_ordinal), allow_software_fallback=True,+ options={"primary_ctx": "1"}, is_hw_owned=True,+ )+ encode_device = HWAccel(+ "cuda", device=str(encode_ordinal), options={"primary_ctx": "1"}, is_hw_owned=True,+ )+ decoded_container = av.open(str(source), hwaccel=decode_device)+ input_stream = decoded_container.streams.video[0]+ input_stream.thread_type = "AUTO"+ decoder = iter(decoded_container.decode(input_stream))+ decode_start = time.perf_counter()+ try:+ first_frame = next(decoder)+ except StopIteration as exc:+ raise ValueError("The input contains no decodable video frames.") from exc+ timings["decode_seconds"] += time.perf_counter() - decode_start+ if options.engine == "DLSS" and first_frame.format.name != "cuda":+ raise DLSSNeedsHostFallback("NVDEC did not expose a CUDA frame.")++ encoded_container = av.open(str(temp_video), mode="w")+ output_stream = encoded_container.add_stream(codec_name, rate=metadata["rate"], hwaccel=encode_device)+ output_stream.width, output_stream.height = output_width, output_height+ output_stream.pix_fmt = "cuda"+ output_stream.codec_context.sw_format = "p010le" if output_p010 else "nv12"+ output_stream.time_base = input_stream.time_base+ output_stream.codec_context.time_base = input_stream.time_base+ encoder_options = {+ "preset": "p6", "rc": "vbr", "gpu": str(encode_ordinal),+ # Keep the production encoder's normal B-frame structure. Bound+ # submission/output buffering to the bridge's eight externally+ # owned surfaces without changing p6/HQ/rate-control decisions.+ "rc-lookahead": "0", "surfaces": "8", "delay": "3",+ }+ if codec_name != "av1_nvenc":+ encoder_options["tune"] = "hq"+ if quality["mode"] == "constant-quality":+ encoder_options["cq"] = "0"+ output_stream.codec_context.bit_rate = 0+ else:+ output_stream.codec_context.bit_rate = int(quality["target_bitrate_kbps"]) * 1000+ output_stream.codec_context.options = encoder_options+ _set_color_properties(output_stream.codec_context, bool(options.hdr_enabled))+ # Force decoder and encoder CUDA contexts to exist before NGX.+ output_stream.codec_context.open()+ if options.engine == "DLSS":+ capabilities = (capabilities or probe_capabilities(+ options.ai_gpu_uuid, controller=controller)) if options.hdr_enabled else None+ session = _DLSSVideoAdapter(+ width, height, options, output_p010, controller, capabilities)+ else:+ capabilities = capabilities or probe_capabilities(options.ai_gpu_uuid, controller=controller)+ session = RTXVideoSession(+ width, height, output_width, output_height, options, input_format,+ capabilities, controller)+ if encode_ordinal != ai_ordinal:+ transfer_pool = CudaTransferPool(ai_ordinal, encode_ordinal, controller)++ decode_queue: queue.Queue = queue.Queue(maxsize=4)+ encode_queue: queue.Queue = queue.Queue(maxsize=4)++ def decode_worker() -> None:+ def put_decode(item: Any) -> bool:+ while not stop.is_set() and not decode_stop.is_set():+ if controller.cancel.is_set() or failures:+ stop.set()+ return False+ try:+ decode_queue.put(item, timeout=0.05)+ return True+ except queue.Full:+ continue+ return False++ try:+ if not put_decode(first_frame):+ return+ while not stop.is_set() and not decode_stop.is_set():+ tick = time.perf_counter()+ try:+ frame = next(decoder)+ except StopIteration:+ timings["decode_seconds"] += time.perf_counter() - tick+ break+ timings["decode_seconds"] += time.perf_counter() - tick+ if frame.is_corrupt:+ raise RuntimeError("The video decoder returned a corrupt frame.")+ if not put_decode(frame):+ return+ except BaseException as exc:+ failures.append(exc); stop.set()+ finally:+ if not decode_stop.is_set():+ put_decode(_END)++ encoded_frames = [0]++ def encode_worker() -> None:+ try:+ while not stop.is_set():+ item = _get_bounded(encode_queue, stop, controller, failures)+ if item is _END:+ break+ tick = time.perf_counter()+ for packet in output_stream.encode(item):+ encoded_container.mux(packet)+ timings["encode_seconds"] += time.perf_counter() - tick+ encoded_frames[0] += 1+ del item+ if not failures and not controller.cancel.is_set():+ tick = time.perf_counter()+ for packet in output_stream.encode():+ encoded_container.mux(packet)+ timings["encode_seconds"] += time.perf_counter() - tick+ except BaseException as exc:+ failures.append(exc); stop.set()++ decode_thread = threading.Thread(target=decode_worker, name="rtx-video-decoder", daemon=True)+ encode_thread = threading.Thread(target=encode_worker, name="rtx-video-encoder", daemon=True)+ pipeline_started = time.perf_counter()+ decode_thread.start(); encode_thread.start()++ stream_tb = input_stream.time_base or Fraction(1, max(1, round(float(metadata["rate"]))))+ default_duration = max(1, round(Fraction(1, 1) / metadata["rate"] / stream_tb))+ origin_pts = round(Fraction(str(metadata["origin"])) / stream_tb)+ first_time: Fraction | None = None+ preview_pts_origin: int | None = None+ last_pts: int | None = None+ stopped_early = False+ timestamp_fallbacks = 0+ estimated = int(metadata["frames"] or max(1, math.ceil(metadata["duration"] * float(metadata["rate"]))))+ if options.preview_frames is not None:+ estimated = min(estimated, int(options.preview_frames))+ elif options.preview_seconds is not None:+ estimated = min(estimated, max(1, math.ceil(options.preview_seconds * float(metadata["rate"]))))+ last_update = 0.0+ while True:+ frame = _get_bounded(decode_queue, stop, controller, failures)+ if frame is _END:+ break+ pts, duration, used_fallback = normalize_frame_timing(+ frame_pts=frame.pts, frame_duration=frame.duration,+ frame_time_base=frame.time_base, stream_time_base=stream_tb,+ origin_pts=origin_pts, delivered=delivered,+ default_duration=default_duration, last_pts=last_pts,+ )+ frame_tb = frame.time_base or stream_tb+ timestamp_fallbacks += int(used_fallback)+ timestamp = Fraction(pts) * stream_tb+ if first_time is None:+ first_time = timestamp+ if ((options.preview_frames is not None and delivered >= int(options.preview_frames)) or+ (options.preview_seconds is not None and delivered and+ float(timestamp - first_time) >= float(options.preview_seconds))):+ stopped_early = True+ decode_stop.set()+ del frame+ break+ if frame.format.name == "cuda":+ decode_backends.add("nvdec")+ processed, detail = session.process_cuda_frame(+ frame, color_matrix=_matrix_code(metadata), color_range=_range_code(metadata),+ color_primaries=_primaries_code(metadata), color_transfer=_transfer_code(metadata),+ chroma_location=_chroma_location_code(metadata),+ rotation=int(metadata["rotation"]), output_p010=output_p010,+ )+ else:+ if options.engine == "DLSS":+ raise RuntimeError("DLSS CUDA decoding changed to software mid-stream.")+ raise DLSSNeedsHostFallback("Vulkan host decoding is required for this input.")+ if transfer_pool is not None:+ transferred, transfer_detail = transfer_pool.transfer(processed)+ del processed+ processed = transferred+ timings["cross_gpu_seconds"] = (+ timings.get("cross_gpu_seconds", 0.0) ++ float(transfer_detail["copy_ms"]) / 1000.0+ )+ timings["bridge_input_seconds"] += detail["input_ms"] / 1000.0+ timings["ngx_seconds"] += detail["ngx_ms"] / 1000.0+ timings["bridge_output_seconds"] += detail["output_ms"] / 1000.0+ if preview:+ if preview_pts_origin is None:+ preview_pts_origin = pts+ processed.pts = pts - preview_pts_origin+ else:+ processed.pts = pts+ processed.time_base = stream_tb+ processed.duration = duration+ if not _put_bounded(encode_queue, processed, stop, controller, failures):+ raise failures[0] if failures else Cancelled("Upscale stopped by user.")+ delivered += 1+ last_pts = pts+ del frame, processed+ now = time.perf_counter()+ if now - last_update > 0.2:+ update(+ min(0.87, 0.05 + 0.82 * delivered / max(1, estimated)),+ f"Upscaling video: {delivered:,} / {estimated:,} frames",+ )+ last_update = now+ if not delivered:+ raise ValueError("The input contains no decodable video frames.")+ _put_bounded(encode_queue, _END, threading.Event(), controller, failures)+ decode_thread.join(timeout=30)+ encode_thread.join(timeout=180)+ if decode_thread.is_alive() or encode_thread.is_alive():+ raise RuntimeError("The bounded RTX Video pipeline did not drain cleanly.")+ timings["pipeline_seconds"] = time.perf_counter() - pipeline_started+ if failures:+ raise failures[0]+ if encoded_frames[0] != delivered:+ raise RuntimeError(f"NVENC accepted {encoded_frames[0]} frames instead of {delivered}.")+ encoded_container.close(); encoded_container = None+ decoded_container.close(); decoded_container = None+ gc.collect()+ transfer_diagnostics = transfer_pool.diagnostics() if transfer_pool is not None else {}+ if transfer_pool is not None:+ transfer_pool.close()+ transfer_pool = None+ session_status = session.structured_status(+ decode_backend="+".join(sorted(decode_backends)) or "unknown",+ encode_backend=codec_name,+ )+ session.close()+ if session.completed_frames != delivered:+ raise RuntimeError("GPU bridge completion does not match frame accounting.")+ gc.collect()++ if not preview and (not metadata["frames"] or delivered != metadata["frames"]):+ exact = ffmpeg.probe_video(source, count_mode="exact", strict_decode=True, controller=controller)+ if int(exact["frames"]) != delivered:+ raise RuntimeError(f"Source has {exact['frames']} frames but only {delivered} were processed.")+ update(0.90, "Muxing original audio, subtitles, chapters, and metadata")+ mux_started = time.perf_counter()+ audio_diagnostics: dict = {}+ ffmpeg.final_mux(+ temp_video, source, destination_file.temporary, options.container, controller,+ preserve_supported_subtitles=True, source_time_origin=metadata["origin"],+ audio_diagnostics=audio_diagnostics,+ )+ timings["final_mux_seconds"] = time.perf_counter() - mux_started+ update(0.96, "Verifying output frames, resolution, and HDR signaling")+ verified = ffmpeg.probe_video(destination_file.temporary, count_mode="packets", controller=controller)+ if int(verified["frames"]) != delivered:+ verified = ffmpeg.probe_video(+ destination_file.temporary, count_mode="exact", strict_decode=True, controller=controller)+ if int(verified["frames"]) != delivered or (int(verified["width"]), int(verified["height"])) != (output_width, output_height):+ raise RuntimeError("Saved output does not match processed frame count or dimensions.")+ saved = inspect_video(destination_file.temporary, controller)+ if options.hdr_enabled and (+ saved["depth"] < 10 or not saved["hdr"] or+ saved["stream"].get("color_primaries") != "bt2020" or+ saved["stream"].get("color_space") != "bt2020nc"+ ):+ raise RuntimeError("Saved file failed HDR color and bit-depth verification.")+ if not options.hdr_enabled and saved["hdr"]:+ raise RuntimeError("SDR output unexpectedly contains HDR signaling.")+ if controller.cancel.is_set():+ raise Cancelled("Upscale stopped by user.")+ elapsed = time.perf_counter() - started+ stage_per_frame = {+ "decode_ms": timings["decode_seconds"] * 1000 / delivered,+ "bridge_ms": (timings["bridge_input_seconds"] + timings["ngx_seconds"] + timings["bridge_output_seconds"]) * 1000 / delivered,+ "encode_ms": timings["encode_seconds"] * 1000 / delivered,+ }+ slowest_ms = max(stage_per_frame.values())+ ceiling_fps = 1000.0 / slowest_ms if slowest_ms > 0 else 0.0+ throughput = delivered / max(timings["pipeline_seconds"], 1e-9)+ timings.update(+ steady_state_fps=throughput, slowest_stage_ceiling_fps=ceiling_fps,+ ceiling_utilization=throughput / ceiling_fps if ceiling_fps else 0.0,+ timestamp_fallbacks=timestamp_fallbacks,+ )+ session_status["timings"] = dict(timings)+ session_status["adapters"] = {"ai": ai_gpu, "decode": ai_gpu, "encode": video_gpu}+ session_status["audio_streams"] = audio_diagnostics.get("streams", [])+ if transfer_diagnostics:+ session_status["cross_gpu_transfer"] = transfer_diagnostics+ session_status["memory_path"] = transfer_diagnostics["memory_path"]+ session_status["upload_bytes"] = (+ int(session_status.get("upload_bytes", 0)) ++ int(transfer_diagnostics["pinned_upload_bytes"])+ )+ session_status["download_bytes"] = (+ int(session_status.get("download_bytes", 0)) ++ int(transfer_diagnostics["pinned_download_bytes"])+ )+ destination_file.publish()+ app_log.info(+ "upscale-cuda", f"done src={source.name} out={output.name} frames={delivered} "+ f"elapsed={elapsed:.2f}s fps={delivered / max(elapsed, 1e-9):.1f} memory={session_status['memory_path']}",+ )+ update(1.0, "Complete — CUDA-resident RTX Video confirmed")+ return UpscaleResult(+ str(output), report_path, delivered, output_width, output_height,+ options.hdr_enabled, elapsed,+ bridge_version=("DLSS ABI 1" if options.engine == "DLSS" else str(capabilities.bridge_version)),+ memory_path=str(session_status["memory_path"]),+ decode_backend=str(session_status["decode_backend"]),+ encode_backend=codec_name, timings=timings, bridge_status=session_status,+ )+ finally:+ job.cleanup()+ except BaseException:+ stop.set()+ decode_stop.set()+ for thread in (decode_thread, encode_thread):+ if thread is not None:+ thread.join(timeout=2)+ if session is not None and not session.closed:+ with suppress(Exception):+ session.close(abort=True)+ if transfer_pool is not None and not transfer_pool.closed:+ with suppress(Exception):+ transfer_pool.close(abort=True)+ if encoded_container is not None:+ with suppress(Exception):+ encoded_container.close()+ if decoded_container is not None:+ with suppress(Exception):+ decoded_container.close()+ destination_file.cleanup(rollback=True)+ raisediff --git a/src/upscale/video/dlss_pipeline.py b/src/upscale/video/dlss_pipeline.pyindex aab7faa..088fe6f 100644--- a/src/upscale/video/dlss_pipeline.py+++ b/src/upscale/video/dlss_pipeline.py@@ -1,247 +1,251 @@-"""DLSS video route with separate optional RTX Video HDR evaluation."""--from __future__ import annotations--import math-import tempfile-import time-import uuid-from contextlib import suppress-from fractions import Fraction-from pathlib import Path--import av-import cv2-import numpy as np-from av.codec.hwaccel import HWAccel--from ...core import app_log, ffmpeg-from ...core.disk_paths import OutputFile, prepare_output_dir-from ...core.dlss_bridge import DLSSSession-from ...core.gpu_selection import detect_gpu-from ...core.jobs import Cancelled-from ...core.naming import output_filename, unique_output_path-from ...core.paths import JOBS-from ...neural_rendering.video.guides import TemporalGuideGenerator-from .media import inspect_video, result_frame-from .models import UpscaleResult, output_size-from .native import FORMAT_RGBA8, FORMAT_R10, RTXVideoSession, probe_capabilities---def convert_video_dlss(source, options, *, controller, progress=None, output_dir=None,- metadata=None, video_gpu=None):- started = time.perf_counter()- metadata = metadata or inspect_video(source, controller, reject_hdr=True)- width, height = int(metadata["width"]), int(metadata["height"])- ow, oh, _ = output_size(width, height, options)- gpu = detect_gpu(options.ai_gpu_uuid)- ordinal = int(gpu["cuda_ordinal"])- source_high_depth = int(metadata["depth"]) > 8- output_depth = ffmpeg.output_video_depth(metadata["depth"], options.codec, options.hdr_enabled)- preview = options.preview_frames is not None or options.preview_seconds is not None- extension = {"MP4": ".mp4", "MKV": ".mkv", "MOV": ".mov"}[options.container]- stamp = time.strftime("%Y%m%d-%H%M%S") + "-" + uuid.uuid4().hex[:8]- destination = prepare_output_dir(output_dir)- output = unique_output_path(destination / output_filename(- source, extension, "Auto" if preview else options.rename_mode,- options.custom_suffix, f"{source.stem}_DLSS_{stamp}"))- output_file = OutputFile(output)- report_path = app_log.session_path()- input_container = None- encoder = None- writer = None- hdr_session = None- dlss = None- delivered = 0- cuts = 0- timings = {"decode_seconds": 0.0, "dlss_seconds": 0.0,- "hdr_seconds": 0.0, "encode_seconds": 0.0}-- def update(value, message):- if controller.cancel.is_set():- raise Cancelled("DLSS upscale stopped by user.")- if progress:- progress(value, message)-- JOBS.mkdir(exist_ok=True)- try:- with tempfile.TemporaryDirectory(prefix="dlss-video-", dir=JOBS) as work:- temp_video = Path(work) / "encoded.mkv"- update(.01, "Starting DLSS Super Resolution")- dlss = DLSSSession(width, height, options.dlss_mode, options.dlss_preset,- gpu_uuid=options.ai_gpu_uuid, even=True)- if (dlss.output_width, dlss.output_height) != (ow, oh):- raise RuntimeError("DLSS output sizing differs from the video encoder size.")- if options.hdr_enabled:- from dataclasses import replace- caps = probe_capabilities(options.ai_gpu_uuid, controller=controller)- hdr_session = RTXVideoSession(- ow, oh, ow, oh, replace(options, vsr_enabled=False),- FORMAT_R10 if source_high_depth else FORMAT_RGBA8, caps, controller)- encoder, encoder_thread, encoder_logs, selected, quality = ffmpeg.start_encoder(- temp_video, options.codec, options.quality, controller, ow, oh,- float(metadata["rate"]),- None if video_gpu is None else int(video_gpu["cuda_ordinal"]),- video_gpu is not None, hdr_mode=options.hdr_enabled,- hdr_metadata={- "color_space": "bt2020nc" if options.hdr_enabled else "bt709",- "color_primaries": "bt2020" if options.hdr_enabled else "bt709",- "color_transfer": "smpte2084" if options.hdr_enabled else "bt709",- "color_range": "tv", "hdr": options.hdr_enabled,- }, preserve_timestamps=True, bounded_logs=True,- output_depth=output_depth)- decode_device = HWAccel(- "cuda", device=str(ordinal), allow_software_fallback=True,- options={"primary_ctx": "1"}, is_hw_owned=True)- input_container = av.open(str(source), hwaccel=decode_device)- stream = input_container.streams.video[0]- stream.thread_type = "AUTO"- stream_tb = stream.time_base or Fraction(1, max(1, round(float(metadata["rate"]))))- writer = ffmpeg.RawVideoPacketMuxer(- encoder.stdin, width=ow, height=oh, rate=metadata["rate"],- time_base=stream_tb, pix_fmt="rgba64le" if output_depth > 8 else "rgba")- guides = TemporalGuideGenerator(width, height, cut_threshold=0.10)- first_pts = None- last_pts = None- default_duration = max(1, round(Fraction(1) / metadata["rate"] / stream_tb))- estimated = int(metadata["frames"] or max(1, math.ceil(metadata["duration"] * float(metadata["rate"]))))- for frame in input_container.decode(stream):- if frame.is_corrupt:- raise RuntimeError("The source decoder returned a corrupt frame.")- decode_tick = time.perf_counter()- pts = round(Fraction(frame.pts) * (frame.time_base or stream_tb) / stream_tb) if frame.pts is not None else (- 0 if last_pts is None else last_pts + default_duration)- if last_pts is not None and pts <= last_pts:- pts = last_pts + default_duration- if first_pts is None:- first_pts = pts- if ((options.preview_frames is not None and delivered >= int(options.preview_frames)) or- (options.preview_seconds is not None and delivered and- float(Fraction(pts - first_pts) * stream_tb) >= options.preview_seconds)):- break- rgba = frame.to_ndarray(format="rgba64le" if source_high_depth else "rgba")- rotation = int(metadata["rotation"])- if rotation:- rgba = cv2.rotate(rgba, {90: cv2.ROTATE_90_CLOCKWISE,- 180: cv2.ROTATE_180,- 270: cv2.ROTATE_90_COUNTERCLOCKWISE}[rotation])- if rgba.shape[:2] != (height, width):- rgba = cv2.resize(rgba, (width, height), interpolation=cv2.INTER_LANCZOS4)- rgba = np.ascontiguousarray(rgba)- timings["decode_seconds"] += time.perf_counter() - decode_tick- guide = guides.process(rgba)- cuts += int(delivered > 0 and guide.reset)- dlss_tick = time.perf_counter()- result = dlss.process(rgba, reset=guide.reset, phase=delivered)- timings["dlss_seconds"] += time.perf_counter() - dlss_tick- processed_float = np.clip(result.astype(np.float32), 0, 1)- if hdr_session is not None:- hdr_tick = time.perf_counter()- if source_high_depth:- rgb10 = np.rint(processed_float[..., :3] * 1023).astype(np.uint32)- hdr_input = np.ascontiguousarray(- rgb10[..., 0] | (rgb10[..., 1] << 10) |- (rgb10[..., 2] << 20) | np.uint32(3 << 30))- else:- hdr_input = np.rint(processed_float * 255).astype(np.uint8)- hdr_input[..., 3] = 255- hdr_data = hdr_session.process_frame(hdr_input)- hdr_frame = result_frame(hdr_data, ow, oh, 2)- processed = np.ascontiguousarray(hdr_frame.to_ndarray(format="rgba64le"))- timings["hdr_seconds"] += time.perf_counter() - hdr_tick- else:- levels = 65535 if output_depth > 8 else 255- processed = np.rint(processed_float * levels).astype(- np.uint16 if output_depth > 8 else np.uint8)- processed[..., 3] = levels- encode_tick = time.perf_counter()- duration = round(Fraction(frame.duration or default_duration) *- (frame.time_base or stream_tb) / stream_tb)- writer.write(processed, pts - first_pts if preview else pts, max(1, duration))- timings["encode_seconds"] += time.perf_counter() - encode_tick- delivered += 1- last_pts = pts- if delivered % 4 == 0:- update(min(.86, .04 + .82 * delivered / max(1, estimated)), "DLSS video processing")- if not delivered:- raise ValueError("The source contains no decodable video frames.")- writer.close(); writer = None- encoder.stdin.close()- if encoder.wait(timeout=600) != 0:- encoder_thread.join(timeout=2)- raise RuntimeError("Video encoder failed: " + "\n".join(list(encoder_logs)[-20:]))- encoder_thread.join(timeout=2)- controller.unregister(encoder)- encoder = None- input_container.close(); input_container = None- if hdr_session:- if hdr_session.completed_frames != delivered:- raise RuntimeError("RTX Video HDR frame count does not match DLSS output.")- hdr_session.close(); hdr_session = None- if dlss.frames != delivered:- raise RuntimeError("DLSS frame count does not match the source.")- if not preview and (not metadata["frames"] or delivered != metadata["frames"]):- source_count = ffmpeg.probe_video(- source, count_mode="exact", strict_decode=True, controller=controller)- if int(source_count["frames"]) != delivered:- raise RuntimeError(- f"Source has {source_count['frames']} frames but DLSS processed {delivered}.")- render_w, render_h = dlss.last_result.render_width, dlss.last_result.render_height- dlss.close(); dlss = None- update(.90, "Muxing audio and metadata")- audio_info = {}- ffmpeg.final_mux(temp_video, source, output_file.temporary, options.container,- controller, preserve_supported_subtitles=True,- source_time_origin=metadata["origin"], audio_diagnostics=audio_info,- video_color_metadata={- "color_space": "bt2020nc" if options.hdr_enabled else "bt709",- "color_primaries": "bt2020" if options.hdr_enabled else "bt709",- "color_transfer": "smpte2084" if options.hdr_enabled else "bt709",- "color_range": "tv"})- update(.96, "Verifying output")- saved = ffmpeg.probe_video(output_file.temporary, count_mode="exact",- strict_decode=True, controller=controller)- if (int(saved["frames"]) != delivered or- (int(saved["width"]), int(saved["height"])) != (ow, oh)):- raise RuntimeError("DLSS output has an incorrect frame count or size.")- if options.hdr_enabled:- verified = inspect_video(output_file.temporary, controller)- if (not verified["hdr"] or verified["depth"] < 10 or- verified["stream"].get("color_primaries") != "bt2020" or- verified["stream"].get("color_space") != "bt2020nc"):- raise RuntimeError("DLSS → RTX Video HDR output lost HDR signaling.")- elapsed = time.perf_counter() - started- status = {- "engine": "DLSS Super Resolution", "mode": options.dlss_mode,- "preset": options.dlss_preset, "guide_estimated": True,- "media_pipeline": "source-anchored DLSS", "synthetic_jitter": False,- "render_width": render_w, "render_height": render_h,- "gpu_pre_resize": (render_w, render_h) != (width, height),- "scene_cuts": cuts, "frames": delivered,- "rtx_video_hdr": bool(options.hdr_enabled),- "audio_streams": audio_info.get("streams", []),- "timings": timings,- }- output_file.publish()- app_log.info("upscale-dlss", f"done src={source.name} out={output.name} frames={delivered} mode={options.dlss_mode} preset={options.dlss_preset} fps={delivered/max(elapsed, 1e-9):.2f}")- update(1.0, "Complete — DLSS evaluated")- return UpscaleResult(str(output), report_path, delivered, ow, oh,- options.hdr_enabled, elapsed, bridge_version="DLSS ABI 1",- memory_path="host_rgba_d3d12_host_encoder",- decode_backend="NVDEC/software", encode_backend=selected,- timings=timings, bridge_status=status)- finally:- if writer:- with suppress(Exception): writer.close()- if input_container:- with suppress(Exception): input_container.close()- if hdr_session:- with suppress(Exception): hdr_session.close(abort=True)- if dlss:- dlss.close()- if encoder:- with suppress(Exception):- if encoder.poll() is None: encoder.kill()- encoder.wait(timeout=5)- controller.unregister(encoder)- output_file.cleanup()+"""DLSS video route with separate optional RTX Video HDR evaluation."""++from __future__ import annotations++import math+import tempfile+import time+import uuid+from contextlib import suppress+from fractions import Fraction+from pathlib import Path++import av+from ...core.ffmpeg.frames import open_video_decoder, VideoOutput+import cv2+import numpy as np+from av.codec.hwaccel import HWAccel++from ...core import app_log, ffmpeg+from ...core.disk_paths import OutputFile, prepare_output_dir+from ...core.dlss_bridge import DLSSSession+from ...core.gpu_selection import detect_gpu+from ...core.jobs import Cancelled+from ...core.naming import output_filename, unique_output_path+from ...core.paths import JOBS+from ...neural_rendering.video.guides import TemporalGuideGenerator+from .media import inspect_video, result_frame+from .models import UpscaleResult, output_size+from .native import FORMAT_RGBA8, FORMAT_R10, RTXVideoSession, probe_capabilities+++def convert_video_dlss(source, options, *, controller, progress=None, output_dir=None,+ metadata=None, video_gpu=None):+ started = time.perf_counter()+ metadata = metadata or inspect_video(source, controller, reject_hdr=True)+ width, height = int(metadata["width"]), int(metadata["height"])+ ow, oh, _ = output_size(width, height, options)+ gpu = detect_gpu(options.ai_gpu_uuid)+ ordinal = int(gpu["cuda_ordinal"])+ source_high_depth = int(metadata["depth"]) > 8+ output_depth = ffmpeg.output_video_depth(metadata["depth"], options.codec, options.hdr_enabled)+ preview = options.preview_frames is not None or options.preview_seconds is not None+ extension = {"MP4": ".mp4", "MKV": ".mkv", "MOV": ".mov"}[options.container]+ stamp = time.strftime("%Y%m%d-%H%M%S") + "-" + uuid.uuid4().hex[:8]+ destination = prepare_output_dir(output_dir)+ output = unique_output_path(destination / output_filename(+ source, extension, "Auto" if preview else options.rename_mode,+ options.custom_suffix, f"{source.stem}_DLSS_{stamp}"))+ output_file = OutputFile(output)+ report_path = app_log.session_path()+ input_container = None+ encoder = None+ writer = None+ hdr_session = None+ dlss = None+ delivered = 0+ cuts = 0+ timings = {"decode_seconds": 0.0, "dlss_seconds": 0.0,+ "hdr_seconds": 0.0, "encode_seconds": 0.0}++ def update(value, message):+ if controller.cancel.is_set():+ raise Cancelled("DLSS upscale stopped by user.")+ if progress:+ progress(value, message)++ JOBS.mkdir(exist_ok=True)+ try:+ with tempfile.TemporaryDirectory(prefix="dlss-video-", dir=JOBS) as work:+ temp_video = Path(work) / "encoded.mkv"+ update(.01, "Starting DLSS Super Resolution")+ dlss = DLSSSession(width, height, options.dlss_mode, options.dlss_preset,+ gpu_uuid=options.ai_gpu_uuid, even=True)+ if (dlss.output_width, dlss.output_height) != (ow, oh):+ raise RuntimeError("DLSS output sizing differs from the video encoder size.")+ if options.hdr_enabled:+ from dataclasses import replace+ caps = probe_capabilities(options.ai_gpu_uuid, controller=controller)+ hdr_session = RTXVideoSession(+ ow, oh, ow, oh, replace(options, vsr_enabled=False),+ FORMAT_R10 if source_high_depth else FORMAT_RGBA8, caps, controller)+ encoder, encoder_thread, encoder_logs, selected, quality = ffmpeg.start_encoder(+ temp_video, options.codec, options.quality, controller, ow, oh,+ float(metadata["rate"]),+ None if video_gpu is None else int(video_gpu["cuda_ordinal"]),+ video_gpu is not None, hdr_mode=options.hdr_enabled,+ hdr_metadata={+ "color_space": "bt2020nc" if options.hdr_enabled else "bt709",+ "color_primaries": "bt2020" if options.hdr_enabled else "bt709",+ "color_transfer": "smpte2084" if options.hdr_enabled else "bt709",+ "color_range": "tv", "hdr": options.hdr_enabled,+ }, preserve_timestamps=True, bounded_logs=True,+ output_depth=output_depth)+ decode_device = HWAccel(+ "cuda", device=str(ordinal), allow_software_fallback=True,+ options={"primary_ctx": "1"}, is_hw_owned=True)+ input_container = open_video_decoder(source, controller, pixel_format="rgba64le" if source_high_depth else "rgba")+ stream = input_container.streams.video[0]+ stream.thread_type = "AUTO"+ stream_tb = stream.time_base or Fraction(1, max(1, round(float(metadata["rate"]))))+ writer = ffmpeg.RawVideoPacketMuxer(+ encoder.stdin, width=ow, height=oh, rate=metadata["rate"],+ time_base=stream_tb, pix_fmt="gbrp10le" if hdr_session else "rgba64le" if output_depth > 8 else "rgba")+ guides = TemporalGuideGenerator(width, height, cut_threshold=0.10)+ first_pts = None+ last_pts = None+ default_duration = max(1, round(Fraction(1) / metadata["rate"] / stream_tb))+ estimated = int(metadata["frames"] or max(1, math.ceil(metadata["duration"] * float(metadata["rate"]))))+ for frame in input_container.decode(stream):+ if frame.is_corrupt:+ raise RuntimeError("The source decoder returned a corrupt frame.")+ decode_tick = time.perf_counter()+ pts = round(Fraction(frame.pts) * (frame.time_base or stream_tb) / stream_tb) if frame.pts is not None else (+ 0 if last_pts is None else last_pts + default_duration)+ if last_pts is not None and pts <= last_pts:+ pts = last_pts + default_duration+ if first_pts is None:+ first_pts = pts+ if ((options.preview_frames is not None and delivered >= int(options.preview_frames)) or+ (options.preview_seconds is not None and delivered and+ float(Fraction(pts - first_pts) * stream_tb) >= options.preview_seconds)):+ break+ rgba = frame.to_ndarray(format="rgba64le" if source_high_depth else "rgba")+ rotation = int(metadata["rotation"])+ if rotation:+ rgba = cv2.rotate(rgba, {90: cv2.ROTATE_90_CLOCKWISE,+ 180: cv2.ROTATE_180,+ 270: cv2.ROTATE_90_COUNTERCLOCKWISE}[rotation])+ if rgba.shape[:2] != (height, width):+ from ...core.ffmpeg.filters import resize_fit+ rgba = resize_fit(rgba, width, height, controller=controller)+ rgba = np.ascontiguousarray(rgba)+ timings["decode_seconds"] += time.perf_counter() - decode_tick+ guide = guides.process(rgba)+ cuts += int(delivered > 0 and guide.reset)+ dlss_tick = time.perf_counter()+ result = dlss.process(rgba, reset=guide.reset, phase=delivered)+ timings["dlss_seconds"] += time.perf_counter() - dlss_tick+ processed_float = np.clip(result.astype(np.float32), 0, 1)+ if hdr_session is not None:+ hdr_tick = time.perf_counter()+ if source_high_depth:+ rgb10 = np.rint(processed_float[..., :3] * 1023).astype(np.uint32)+ hdr_input = np.ascontiguousarray(+ rgb10[..., 0] | (rgb10[..., 1] << 10) |+ (rgb10[..., 2] << 20) | np.uint32(3 << 30))+ else:+ hdr_input = np.rint(processed_float * 255).astype(np.uint8)+ hdr_input[..., 3] = 255+ hdr_data = hdr_session.process_frame(hdr_input)+ hdr_frame = result_frame(hdr_data, ow, oh, 2)+ from ...core.ffmpeg.frames import packed_frame+ processed = packed_frame(hdr_frame)+ timings["hdr_seconds"] += time.perf_counter() - hdr_tick+ else:+ levels = 65535 if output_depth > 8 else 255+ processed = np.rint(processed_float * levels).astype(+ np.uint16 if output_depth > 8 else np.uint8)+ processed[..., 3] = levels+ encode_tick = time.perf_counter()+ duration = round(Fraction(frame.duration or default_duration) *+ (frame.time_base or stream_tb) / stream_tb)+ writer.write(processed, pts - first_pts if preview else pts, max(1, duration))+ timings["encode_seconds"] += time.perf_counter() - encode_tick+ delivered += 1+ last_pts = pts+ if delivered % 4 == 0:+ update(min(.86, .04 + .82 * delivered / max(1, estimated)),+ f"DLSS video processing: {delivered:,} / {estimated:,} frames")+ if not delivered:+ raise ValueError("The source contains no decodable video frames.")+ writer.close(); writer = None+ encoder.stdin.close()+ if encoder.wait(timeout=600) != 0:+ encoder_thread.join(timeout=2)+ raise RuntimeError("Video encoder failed: " + "\n".join(list(encoder_logs)[-20:]))+ encoder_thread.join(timeout=2)+ controller.unregister(encoder)+ encoder = None+ input_container.close(); input_container = None+ if hdr_session:+ if hdr_session.completed_frames != delivered:+ raise RuntimeError("RTX Video HDR frame count does not match DLSS output.")+ hdr_session.close(); hdr_session = None+ if dlss.frames != delivered:+ raise RuntimeError("DLSS frame count does not match the source.")+ if not preview and (not metadata["frames"] or delivered != metadata["frames"]):+ source_count = ffmpeg.probe_video(+ source, count_mode="exact", strict_decode=True, controller=controller)+ if int(source_count["frames"]) != delivered:+ raise RuntimeError(+ f"Source has {source_count['frames']} frames but DLSS processed {delivered}.")+ render_w, render_h = dlss.last_result.render_width, dlss.last_result.render_height+ dlss.close(); dlss = None+ update(.90, "Muxing audio and metadata")+ audio_info = {}+ ffmpeg.final_mux(temp_video, source, output_file.temporary, options.container,+ controller, preserve_supported_subtitles=True,+ source_time_origin=metadata["origin"], audio_diagnostics=audio_info,+ video_color_metadata={+ "color_space": "bt2020nc" if options.hdr_enabled else "bt709",+ "color_primaries": "bt2020" if options.hdr_enabled else "bt709",+ "color_transfer": "smpte2084" if options.hdr_enabled else "bt709",+ "color_range": "tv"})+ update(.96, "Verifying output")+ saved = ffmpeg.probe_video(output_file.temporary, count_mode="exact",+ strict_decode=True, controller=controller)+ if (int(saved["frames"]) != delivered or+ (int(saved["width"]), int(saved["height"])) != (ow, oh)):+ raise RuntimeError("DLSS output has an incorrect frame count or size.")+ if options.hdr_enabled:+ verified = inspect_video(output_file.temporary, controller)+ if (not verified["hdr"] or verified["depth"] < 10 or+ verified["stream"].get("color_primaries") != "bt2020" or+ verified["stream"].get("color_space") != "bt2020nc"):+ raise RuntimeError("DLSS → RTX Video HDR output lost HDR signaling.")+ elapsed = time.perf_counter() - started+ status = {+ "engine": "DLSS Super Resolution", "mode": options.dlss_mode,+ "preset": options.dlss_preset, "guide_estimated": True,+ "media_pipeline": "source-anchored DLSS", "synthetic_jitter": False,+ "render_width": render_w, "render_height": render_h,+ "gpu_pre_resize": (render_w, render_h) != (width, height),+ "scene_cuts": cuts, "frames": delivered,+ "rtx_video_hdr": bool(options.hdr_enabled),+ "audio_streams": audio_info.get("streams", []),+ "timings": timings,+ }+ output_file.publish()+ app_log.info("upscale-dlss", f"done src={source.name} out={output.name} frames={delivered} mode={options.dlss_mode} preset={options.dlss_preset} fps={delivered/max(elapsed, 1e-9):.2f}")+ update(1.0, "Complete — DLSS evaluated")+ return UpscaleResult(str(output), report_path, delivered, ow, oh,+ options.hdr_enabled, elapsed, bridge_version="DLSS ABI 1",+ memory_path="host_rgba_d3d12_host_encoder",+ decode_backend="NVDEC/software", encode_backend=selected,+ timings=timings, bridge_status=status)+ finally:+ if writer:+ with suppress(Exception): writer.close()+ if input_container:+ with suppress(Exception): input_container.close()+ if hdr_session:+ with suppress(Exception): hdr_session.close(abort=True)+ if dlss:+ dlss.close()+ if encoder:+ with suppress(Exception):+ if encoder.poll() is None: encoder.kill()+ encoder.wait(timeout=5)+ controller.unregister(encoder)+ output_file.cleanup()diff --git a/src/upscale/video/host_pipeline.py b/src/upscale/video/host_pipeline.pyindex 46c96be..be8a78c 100644--- a/src/upscale/video/host_pipeline.py+++ b/src/upscale/video/host_pipeline.py@@ -1,685 +1,672 @@-from __future__ import annotations--"""In-process NVDEC/software -> RTX Video -> pinned host -> CPU encoder pipeline."""--import ctypes-import gc-import math-import os-import queue-import tempfile-import threading-import time-import uuid-from contextlib import suppress-from dataclasses import dataclass-from fractions import Fraction-from pathlib import Path-from typing import Any, Callable--import av-from av.codec.hwaccel import HWAccel--from ...core import app_log, ffmpeg-from ...core.disk_paths import OutputFile, prepare_output_dir-from ...core.jobs import Cancelled-from ...core.naming import output_filename, unique_output_path-from ...core.paths import JOBS-from ...core.ffmpeg.codecs import _x265_hdr_params-from .cuda_pipeline import (- _END,- _SoftwareNormalizer,- _chroma_location_code,- _get_bounded,- _matrix_code,- _primaries_code,- _put_bounded,- _range_code,- _set_color_properties,- _transfer_code,- normalize_frame_timing,-)-from .cuda_transfer import CU_MEMHOSTALLOC_PORTABLE, _CudaApi-from .media import inspect_video, packed_bytes-from .models import UpscaleCapabilities, UpscaleOptions, UpscaleResult, output_size-from .native import (- FORMAT_NV12,- FORMAT_P010,- FORMAT_YUV422P10,- RTXVideoSession,- probe_capabilities,-)---@dataclass(slots=True)-class _EncoderSettings:- codec: str- display_name: str- pixel_format: str- native_format: int- options: dict[str, str]- bit_rate: int- quality: dict[str, Any]---def _codec_available(name: str) -> bool:- try:- av.codec.Codec(name, "w")- return True- except Exception:- return False---def _encoder_settings(options: UpscaleOptions, width: int, height: int,- rate: Fraction, ten_bit: bool) -> _EncoderSettings:- codec = ffmpeg._normalize_codec(options.codec)- quality = ffmpeg.resolve_encoding_quality(- options.quality, options.codec, width, height, float(rate), hdr_mode=ten_bit)- bit_rate = int(quality.get("target_bitrate_kbps") or 0) * 1000- common: dict[str, str] = {}- if quality["mode"] == "constant-quality":- common["crf"] = "0"- if codec == "H.264":- return _EncoderSettings(- "libx264", "libx264", "yuv420p", FORMAT_NV12,- {"preset": "slow", **common}, bit_rate, quality)- if codec in {"H.265", "HEVC"}:- values = {"preset": "slow", **common}- if options.hdr_enabled:- colors = {"color_space": "bt2020nc", "color_transfer": "smpte2084",- "color_primaries": "bt2020", "hdr": True}- hdr_parameters = _x265_hdr_params(colors)- if hdr_parameters:- values["x265-params"] = hdr_parameters- return _EncoderSettings(- "libx265", "libx265", "yuv420p10le" if ten_bit else "yuv420p",- FORMAT_P010 if ten_bit else FORMAT_NV12, values, bit_rate, quality)- if codec == "AV1":- encoder = "libsvtav1" if _codec_available("libsvtav1") else "libaom-av1"- if not _codec_available(encoder):- raise RuntimeError(- "AV1 CPU encoding is unavailable: neither libsvtav1 nor libaom-av1 can initialize.")- values = ({"preset": "6"} if encoder == "libsvtav1" else {"cpu-used": "4"})- values.update(common)- if encoder == "libaom-av1" and quality["mode"] == "constant-quality":- values["b"] = "0"- return _EncoderSettings(- encoder, encoder, "yuv420p10le" if ten_bit else "yuv420p",- FORMAT_P010 if ten_bit else FORMAT_NV12, values, bit_rate, quality)- if codec == "ProRes Proxy":- values = {"profile": "0"}- if quality.get("bits_per_mb") is not None:- values["bits_per_mb"] = str(int(quality["bits_per_mb"]))- return _EncoderSettings(- "prores_ks", "prores_ks (Proxy)", "yuv422p10le",- FORMAT_YUV422P10, values, 0, quality)- if codec == "ProRes HQ":- return _EncoderSettings(- "prores_ks", "prores_ks (HQ)", "yuv422p10le",- FORMAT_YUV422P10, {"profile": "3"}, 0, quality)- if codec == "FFV1 Lossless RGB 10-bit":- return _EncoderSettings(- "ffv1", "ffv1 (Lossless RGB 10-bit)", "gbrp10le", FORMAT_YUV422P10,- {"level": "3", "slicecrc": "1"}, 0, quality)- raise ValueError(f"The in-process host pipeline does not support codec {options.codec!r}.")---@dataclass(slots=True)-class _PinnedSlot:- owner: "_PinnedFramePool"- pointer: int- plane_pointers: tuple[int, ...]- strides: tuple[int, ...]- rows: tuple[int, ...]- row_bytes: tuple[int, ...]- held: bool = False- pts: int | None = None- duration: int | None = None- time_base: Fraction | None = None-- def release(self) -> None:- with self.owner.condition:- if self.held:- self.held = False- self.owner.condition.notify_all()-- def to_av_frame(self) -> tuple[av.VideoFrame, float]:- tick = time.perf_counter()- try:- frame = av.VideoFrame(self.owner.width, self.owner.height, self.owner.pixel_format)- for index, plane in enumerate(frame.planes):- source = self.plane_pointers[index]- source_stride = self.strides[index]- count = self.row_bytes[index]- rows = self.rows[index]- destination = int(plane.buffer_ptr)- destination_stride = int(plane.line_size)- if count == source_stride == destination_stride:- ctypes.memmove(destination, source, count * rows)- else:- for row in range(rows):- ctypes.memmove(destination + row * destination_stride,- source + row * source_stride, count)- frame.pts, frame.time_base = self.pts, self.time_base- if self.duration is not None:- frame.duration = self.duration- return frame, time.perf_counter() - tick- finally:- self.release()---class _PinnedFramePool:- """Four preallocated page-locked frames shared by RTX and encoder stages."""-- def __init__(self, ordinal: int, width: int, height: int, native_format: int,- pixel_format: str, controller: Any, *, capacity: int = 4,- timeout: float = 180.0) -> None:- self.api = _CudaApi()- self.ordinal, self.width, self.height = int(ordinal), int(width), int(height)- self.native_format, self.pixel_format = int(native_format), str(pixel_format)- self.controller, self.capacity, self.timeout = controller, int(capacity), float(timeout)- self.condition = threading.Condition()- self.pool_waits = 0- self.closed = False- self.device = self.api.device(self.ordinal)- self.context = self.api.primary_context(self.device)- if native_format == FORMAT_NV12:- strides = (width, width)- rows = (height, (height + 1) // 2)- row_bytes = strides- elif native_format == FORMAT_P010:- strides = (width * 2, width * 2)- rows = (height, (height + 1) // 2)- row_bytes = strides- elif native_format == FORMAT_YUV422P10:- strides = (width * 2, ((width + 1) // 2) * 2, ((width + 1) // 2) * 2)- rows = (height, height, height)- row_bytes = strides- else:- self.api.check(self.api.primary_release(self.device), "cuDevicePrimaryCtxRelease")- raise ValueError("Unsupported pinned-frame format.")- self.frame_bytes = sum(stride * count for stride, count in zip(strides, rows))- self.slots: list[_PinnedSlot] = []- try:- with self.api.current(self.context):- for _ in range(self.capacity):- allocation = ctypes.c_void_p()- self.api.check(self.api.cuMemHostAlloc(- ctypes.byref(allocation), self.frame_bytes, CU_MEMHOSTALLOC_PORTABLE),- "cuMemHostAlloc(encoder frame)")- base = int(allocation.value or 0)- pointers, offset = [], 0- for stride, count in zip(strides, rows):- pointers.append(base + offset)- offset += stride * count- self.slots.append(_PinnedSlot(- self, base, tuple(pointers), tuple(strides), tuple(rows),- tuple(row_bytes)))- except BaseException:- self.close(abort=True)- raise-- def acquire(self) -> _PinnedSlot:- deadline = time.monotonic() + self.timeout- with self.condition:- while True:- if self.controller.cancel.is_set():- raise Cancelled("Upscale stopped by user.")- for slot in self.slots:- if not slot.held:- slot.held = True- return slot- self.pool_waits += 1- remaining = deadline - time.monotonic()- if remaining <= 0:- raise RuntimeError("Pinned encoder-frame pool remained exhausted.")- self.condition.wait(timeout=min(0.05, remaining))-- def diagnostics(self) -> dict[str, Any]:- return {- "surface_pool_capacity": self.capacity,- "surface_pool_allocated": len(self.slots),- "surface_pool_waits": self.pool_waits,- "bytes_per_surface": self.frame_bytes,- "allocation": "cuda_page_locked_host",- }-- def close(self, *, abort: bool = False) -> None:- if self.closed:- return- deadline = time.monotonic() + (2.0 if abort else self.timeout)- with self.condition:- while any(slot.held for slot in self.slots):- remaining = deadline - time.monotonic()- if remaining <= 0:- if abort:- self.closed = True- return- raise RuntimeError("Encoder retained pinned frames past shutdown.")- self.condition.wait(timeout=min(0.05, remaining))- try:- with self.api.current(self.context):- for slot in self.slots:- if slot.pointer:- self.api.check(self.api.cuMemFreeHost(ctypes.c_void_p(slot.pointer)),- "cuMemFreeHost(encoder frame)")- slot.pointer = 0- finally:- self.api.check(self.api.primary_release(self.device), "cuDevicePrimaryCtxRelease")- self.closed = True---def convert_video_inprocess_host(- source: Path,- options: UpscaleOptions,- *,- controller: Any,- progress: Callable[[float, str], None] | None,- output_dir: str | os.PathLike[str] | None,- metadata: dict[str, Any] | None = None,- capabilities: UpscaleCapabilities | None = None,-) -> UpscaleResult:- """Run CPU/ProRes encoding without raw frame or NUT subprocess pipes."""- started = time.perf_counter()- report_path = app_log.session_path()- metadata = metadata or inspect_video(source, controller, reject_hdr=True)- width, height = int(metadata["width"]), int(metadata["height"])- output_width, output_height, _ = output_size(width, height, options)- capabilities = capabilities or probe_capabilities(options.ai_gpu_uuid, controller=controller)- ai_gpu = capabilities.gpu- ordinal = int(ai_gpu["cuda_ordinal"])- input_format = 2 if int(metadata["depth"]) > 8 else 1- ten_bit = bool(- options.hdr_enabled or- (input_format == 2 and ffmpeg.hdr_mode_supported(options.codec)) or- ffmpeg._normalize_codec(options.codec) in {- "ProRes Proxy", "ProRes HQ", "FFV1 Lossless RGB 10-bit"- })- encoder = _encoder_settings(options, output_width, output_height, metadata["rate"], ten_bit)- preview = options.preview_frames is not None or options.preview_seconds is not None- stamp = time.strftime("%Y%m%d-%H%M%S") + "-" + uuid.uuid4().hex[:8]- extension = {"MP4": ".mp4", "MKV": ".mkv", "MOV": ".mov"}[options.container]- destination = prepare_output_dir(output_dir)- kind = "RTXVIDEO_PREVIEW" if preview else "RTXVIDEO"- output = unique_output_path(destination / output_filename(- source, extension, "Auto" if preview else options.rename_mode,- options.custom_suffix, f"{source.stem}_{kind}_{stamp}"))- destination_file = OutputFile(output)- decoded_container: Any | None = None- encoded_container: Any | None = None- session: RTXVideoSession | None = None- pinned_pool: _PinnedFramePool | None = None- decode_thread: threading.Thread | None = None- encode_thread: threading.Thread | None = None- failures: list[BaseException] = []- stop, decode_stop = threading.Event(), threading.Event()- delivered = 0- decode_backends: set[str] = set()- timings: dict[str, float] = {- "decode_seconds": 0.0, "software_prepare_seconds": 0.0,- "bridge_input_seconds": 0.0, "ngx_seconds": 0.0,- "bridge_output_seconds": 0.0, "host_copy_seconds": 0.0,- "encode_seconds": 0.0,- }-- def update(value: float, message: str) -> None:- if controller.cancel.is_set():- raise Cancelled("Upscale stopped by user.")- if progress:- progress(max(0.0, min(1.0, value)), message)-- def drain_slots(target: queue.Queue | None) -> None:- if target is None:- return- while True:- try:- item = target.get_nowait()- except queue.Empty:- return- if isinstance(item, _PinnedSlot):- item.release()-- encode_queue: queue.Queue | None = None- try:- update(0.01, "Preparing video processing")- JOBS.mkdir(exist_ok=True)- job = tempfile.TemporaryDirectory(prefix="rtx-video-host-", dir=JOBS)- try:- job_dir = Path(job.name)- temp_video = job_dir / (- "encoded.mkv" if encoder.codec == "ffv1" else- "encoded.mov" if encoder.codec == "prores_ks" else "encoded.mp4"- )- decode_device = HWAccel(- "cuda", device=str(ordinal), allow_software_fallback=True,- options={"primary_ctx": "1"}, is_hw_owned=True)- decoded_container = av.open(str(source), hwaccel=decode_device)- input_stream = decoded_container.streams.video[0]- input_stream.thread_type = "AUTO"- decoder_iterator = iter(decoded_container.decode(input_stream))- tick = time.perf_counter()- try:- first_frame = next(decoder_iterator)- except StopIteration as exc:- raise ValueError("The input contains no decodable video frames.") from exc- timings["decode_seconds"] += time.perf_counter() - tick-- encoded_container = av.open(str(temp_video), mode="w")- output_stream = encoded_container.add_stream(encoder.codec, rate=metadata["rate"])- output_stream.width, output_stream.height = output_width, output_height- output_stream.pix_fmt = encoder.pixel_format- stream_tb = input_stream.time_base or Fraction(1, max(1, round(float(metadata["rate"]))))- output_stream.time_base = stream_tb- output_stream.codec_context.time_base = stream_tb- output_stream.codec_context.options = encoder.options- output_stream.codec_context.bit_rate = encoder.bit_rate- _set_color_properties(output_stream.codec_context, bool(options.hdr_enabled))- if encoder.codec == "ffv1":- output_stream.codec_context.colorspace = 0- output_stream.codec_context.color_range = 2- output_stream.codec_context.open()-- session = RTXVideoSession(- width, height, output_width, output_height, options, input_format,- capabilities, controller)- pinned_pool = _PinnedFramePool(- ordinal, output_width, output_height, encoder.native_format,- {FORMAT_NV12: "nv12", FORMAT_P010: "p010le",- FORMAT_YUV422P10: "yuv422p10le"}[encoder.native_format], controller)- decode_queue: queue.Queue = queue.Queue(maxsize=4)- encode_queue = queue.Queue(maxsize=4)-- def decode_worker() -> None:- def put(item: Any) -> bool:- while not stop.is_set() and not decode_stop.is_set():- if controller.cancel.is_set() or failures:- stop.set()- return False- try:- decode_queue.put(item, timeout=0.05)- return True- except queue.Full:- continue- return False- try:- if not put(first_frame):- return- while not stop.is_set() and not decode_stop.is_set():- frame_tick = time.perf_counter()- try:- frame = next(decoder_iterator)- except StopIteration:- timings["decode_seconds"] += time.perf_counter() - frame_tick- break- timings["decode_seconds"] += time.perf_counter() - frame_tick- if frame.is_corrupt:- raise RuntimeError("The video decoder returned a corrupt frame.")- if not put(frame):- return- except BaseException as exc:- failures.append(exc)- stop.set()- finally:- if not decode_stop.is_set():- put(_END)-- encoded_frames = [0]-- def encode_worker() -> None:- try:- while not stop.is_set():- item = _get_bounded(encode_queue, stop, controller, failures)- if item is _END:- break- encode_tick = time.perf_counter()- frame, copy_seconds = item.to_av_frame()- timings["host_copy_seconds"] += copy_seconds- if frame.format.name != encoder.pixel_format:- copy_tick = time.perf_counter()- frame = frame.reformat(format=encoder.pixel_format)- timings["host_copy_seconds"] += time.perf_counter() - copy_tick- if encoder.codec == "ffv1":- frame.color_primaries = 9 if options.hdr_enabled else 1- frame.color_trc = 16 if options.hdr_enabled else 1- frame.colorspace = 0- frame.color_range = 2- for packet in output_stream.encode(frame):- encoded_container.mux(packet)- timings["encode_seconds"] += time.perf_counter() - encode_tick- encoded_frames[0] += 1- del item, frame- if not failures and not controller.cancel.is_set():- encode_tick = time.perf_counter()- for packet in output_stream.encode():- encoded_container.mux(packet)- timings["encode_seconds"] += time.perf_counter() - encode_tick- except BaseException as exc:- failures.append(exc)- stop.set()-- decode_thread = threading.Thread(target=decode_worker, name="rtx-host-decoder", daemon=True)- encode_thread = threading.Thread(target=encode_worker, name="rtx-host-encoder", daemon=True)- pipeline_started = time.perf_counter()- decode_thread.start()- encode_thread.start()-- default_duration = max(1, round(Fraction(1, 1) / metadata["rate"] / stream_tb))- origin_pts = round(Fraction(str(metadata["origin"])) / stream_tb)- first_time: Fraction | None = None- preview_origin: int | None = None- last_pts: int | None = None- timestamp_fallbacks = 0- stopped_early = False- software_normalizer: _SoftwareNormalizer | None = None- source_dimensions = (int(first_frame.width), int(first_frame.height))- estimated = int(metadata["frames"] or max(- 1, math.ceil(metadata["duration"] * float(metadata["rate"]))))- if options.preview_frames is not None:- estimated = min(estimated, int(options.preview_frames))- elif options.preview_seconds is not None:- estimated = min(estimated, max(- 1, math.ceil(options.preview_seconds * float(metadata["rate"]))))- last_update = 0.0- while True:- frame = _get_bounded(decode_queue, stop, controller, failures)- if frame is _END:- break- if (int(frame.width), int(frame.height)) != source_dimensions:- raise ValueError("Source dimensions changed during decoding.")- pts, duration, used_fallback = normalize_frame_timing(- frame_pts=frame.pts, frame_duration=frame.duration,- frame_time_base=frame.time_base, stream_time_base=stream_tb,- origin_pts=origin_pts, delivered=delivered,- default_duration=default_duration, last_pts=last_pts)- timestamp_fallbacks += int(used_fallback)- timestamp = Fraction(pts) * stream_tb- if first_time is None:- first_time = timestamp- if ((options.preview_frames is not None and delivered >= int(options.preview_frames)) or- (options.preview_seconds is not None and delivered and- float(timestamp - first_time) >= float(options.preview_seconds))):- stopped_early = True- decode_stop.set()- del frame- break- slot = pinned_pool.acquire()- try:- if frame.format.name == "cuda":- decode_backends.add("nvdec")- detail = session.process_cuda_to_host_planar(- frame, output_format=encoder.native_format,- plane_pointers=slot.plane_pointers, strides=slot.strides,- color_matrix=_matrix_code(metadata), color_range=_range_code(metadata),- color_primaries=_primaries_code(metadata),- color_transfer=_transfer_code(metadata),- chroma_location=_chroma_location_code(metadata),- rotation=int(metadata["rotation"]))- else:- decode_backends.add("software")- prepare_tick = time.perf_counter()- if software_normalizer is None:- software_normalizer = _SoftwareNormalizer(- frame, metadata, width, height, input_format == 2)- packed = software_normalizer.convert(frame)- timings["software_prepare_seconds"] += time.perf_counter() - prepare_tick- detail = session.process_host_to_host_planar(- packed, output_format=encoder.native_format,- plane_pointers=slot.plane_pointers, strides=slot.strides)- timings["bridge_input_seconds"] += detail["input_ms"] / 1000.0- timings["ngx_seconds"] += detail["ngx_ms"] / 1000.0- timings["bridge_output_seconds"] += detail["output_ms"] / 1000.0- if preview:- if preview_origin is None:- preview_origin = pts- slot.pts = pts - preview_origin- else:- slot.pts = pts- slot.time_base, slot.duration = stream_tb, duration- if not _put_bounded(encode_queue, slot, stop, controller, failures):- raise failures[0] if failures else Cancelled("Upscale stopped by user.")- except BaseException:- slot.release()- raise- delivered += 1- last_pts = pts- del frame, slot- now = time.perf_counter()- if now - last_update > 0.2:- update(- min(0.87, 0.05 + 0.82 * delivered / max(1, estimated)),- "Upscaling video")- last_update = now- if not delivered:- raise ValueError("The input contains no decodable video frames.")- _put_bounded(encode_queue, _END, threading.Event(), controller, failures)- decode_thread.join(timeout=30)- encode_thread.join(timeout=600)- if decode_thread.is_alive() or encode_thread.is_alive():- raise RuntimeError("The bounded host-encoding pipeline did not drain cleanly.")- timings["pipeline_seconds"] = time.perf_counter() - pipeline_started- if failures:- raise failures[0]- if encoded_frames[0] != delivered:- raise RuntimeError(f"The encoder accepted {encoded_frames[0]} frames instead of {delivered}.")- encoded_container.close()- encoded_container = None- decoded_container.close()- decoded_container = None- gc.collect()- pool_status = pinned_pool.diagnostics()- pinned_pool.close()- pinned_pool = None- session_status = session.structured_status(- decode_backend="+".join(sorted(decode_backends)) or "unknown",- encode_backend=encoder.display_name)- session.close()- if session.completed_frames != delivered:- raise RuntimeError("RTX Video bridge completion does not match frame accounting.")- if not preview and (not metadata["frames"] or delivered != metadata["frames"]):- exact = ffmpeg.probe_video(source, count_mode="exact", strict_decode=True,- controller=controller)- if int(exact["frames"]) != delivered:- raise RuntimeError(- f"Source has {exact['frames']} frames but only {delivered} were processed.")- update(0.90, "Muxing original audio, subtitles, chapters, and metadata")- mux_tick = time.perf_counter()- audio_diagnostics: dict = {}- ffmpeg.final_mux(- temp_video, source, destination_file.temporary, options.container, controller,- preserve_supported_subtitles=True, source_time_origin=metadata["origin"],- audio_diagnostics=audio_diagnostics)- timings["final_mux_seconds"] = time.perf_counter() - mux_tick- update(0.96, "Verifying output frames, resolution, chroma, and HDR signaling")- verified = ffmpeg.probe_video(destination_file.temporary, count_mode="packets",- controller=controller)- if int(verified["frames"]) != delivered:- verified = ffmpeg.probe_video(- destination_file.temporary, count_mode="exact", strict_decode=True,- controller=controller)- if (int(verified["frames"]) != delivered or- (int(verified["width"]), int(verified["height"])) !=- (output_width, output_height)):- raise RuntimeError("Saved output does not match processed frame count or dimensions.")- saved = inspect_video(destination_file.temporary, controller)- if encoder.codec == "prores_ks" and saved["stream"].get("pix_fmt") != "yuv422p10le":- raise RuntimeError("ProRes output did not preserve direct 10-bit 4:2:2 chroma.")- expected = {- "ProRes HQ": ("prores", "yuv422p10le", 10),- "FFV1 Lossless RGB 10-bit": ("ffv1", "gbrp10le", 10),- }.get(ffmpeg._normalize_codec(options.codec))- if expected and (saved["stream"].get("codec_name"), saved["stream"].get("pix_fmt"),- int(saved["depth"])) != expected:- raise RuntimeError(f"Saved output does not match {options.codec}.")- if options.hdr_enabled and (- saved["depth"] < 10 or not saved["hdr"] or- saved["stream"].get("color_primaries") != "bt2020" or- saved["stream"].get("color_space") != (- "gbr" if encoder.codec == "ffv1" else "bt2020nc")):- raise RuntimeError("Saved file failed HDR color and bit-depth verification.")- if not options.hdr_enabled and saved["hdr"]:- raise RuntimeError("SDR output unexpectedly contains HDR signaling.")- if controller.cancel.is_set():- raise Cancelled("Upscale stopped by user.")- elapsed = time.perf_counter() - started- throughput = delivered / max(timings["pipeline_seconds"], 1e-9)- bridge_seconds = (timings["bridge_input_seconds"] + timings["ngx_seconds"] +- timings["bridge_output_seconds"])- stage_ms = {- "decode_ms": timings["decode_seconds"] * 1000 / delivered,- "bridge_ms": bridge_seconds * 1000 / delivered,- "encode_ms": timings["encode_seconds"] * 1000 / delivered,- }- slowest_ms = max(stage_ms.values())- ceiling_fps = 1000.0 / slowest_ms if slowest_ms else 0.0- timings.update(- steady_state_fps=throughput,- slowest_stage_ceiling_fps=ceiling_fps,- ceiling_utilization=throughput / ceiling_fps if ceiling_fps else 0.0,- timestamp_fallbacks=timestamp_fallbacks)- memory_path = (- "cuda_to_pinned_host"- if decode_backends == {"nvdec"}- else "host_upload_cuda_to_pinned_host"- )- session_status["timings"] = dict(timings)- session_status["memory_path"] = memory_path- session_status["pinned_pool"] = pool_status- session_status["adapters"] = {"ai": ai_gpu, "decode": ai_gpu, "encode": "CPU"}- session_status["audio_streams"] = audio_diagnostics.get("streams", [])- destination_file.publish()- app_log.info(- "upscale-host", f"done src={source.name} out={output.name} frames={delivered} "- f"elapsed={elapsed:.2f}s fps={delivered / max(elapsed, 1e-9):.1f} "- f"encoder={encoder.display_name}")- update(1.0, "Complete — in-process pinned RTX Video path confirmed")- return UpscaleResult(- str(output), report_path, delivered, output_width, output_height,- options.hdr_enabled, elapsed,- bridge_version=str(capabilities.bridge_version),- memory_path=memory_path,- decode_backend="+".join(sorted(decode_backends)) or "unknown",- encode_backend=encoder.display_name, timings=timings,- bridge_status=session_status)- finally:- job.cleanup()- except BaseException:- stop.set()- decode_stop.set()- for thread in (decode_thread, encode_thread):- if thread is not None:- thread.join(timeout=2)- drain_slots(encode_queue)- if encoded_container is not None:- with suppress(Exception):- encoded_container.close()- if decoded_container is not None:- with suppress(Exception):- decoded_container.close()- if session is not None and not session.closed:- with suppress(Exception):- session.close(abort=True)- if pinned_pool is not None and not pinned_pool.closed:- with suppress(Exception):- pinned_pool.close(abort=True)- destination_file.cleanup(rollback=True)- raise+from __future__ import annotations++"""FFmpeg Vulkan/software -> RTX Video -> pinned host -> FFmpeg codec pipeline."""++import ctypes+import gc+import math+import os+import queue+import tempfile+import threading+import time+import uuid+from contextlib import suppress+from dataclasses import dataclass+from fractions import Fraction+from pathlib import Path+from typing import Any, Callable++import av+from ...core.ffmpeg.frames import open_video_decoder, VideoOutput+from av.codec.hwaccel import HWAccel++from ...core import app_log, ffmpeg+from ...core.disk_paths import OutputFile, prepare_output_dir+from ...core.jobs import Cancelled+from ...core.naming import output_filename, unique_output_path+from ...core.paths import JOBS+from ...core.ffmpeg.codecs import _x265_hdr_params+from .cuda_pipeline import (+ _END,+ _chroma_location_code,+ _get_bounded,+ _matrix_code,+ _primaries_code,+ _put_bounded,+ _range_code,+ _set_color_properties,+ _transfer_code,+ normalize_frame_timing,+)+from .cuda_transfer import CU_MEMHOSTALLOC_PORTABLE, _CudaApi+from .media import inspect_video, packed_bytes+from .models import UpscaleCapabilities, UpscaleOptions, UpscaleResult, output_size+from .native import (+ FORMAT_NV12,+ FORMAT_P010,+ FORMAT_YUV422P10,+ RTXVideoSession,+ probe_capabilities,+)+++@dataclass(slots=True)+class _EncoderSettings:+ codec: str+ display_name: str+ pixel_format: str+ native_format: int+ options: dict[str, str]+ bit_rate: int+ quality: dict[str, Any]+++def _codec_available(name: str) -> bool:+ from ...core.ffmpeg.vulkan import ffmpeg_encoders+ return name in ffmpeg_encoders()+++def _encoder_settings(options: UpscaleOptions, width: int, height: int,+ rate: Fraction, ten_bit: bool) -> _EncoderSettings:+ codec = ffmpeg._normalize_codec(options.codec)+ quality = ffmpeg.resolve_encoding_quality(+ options.quality, options.codec, width, height, float(rate), hdr_mode=ten_bit)+ bit_rate = int(quality.get("target_bitrate_kbps") or 0) * 1000+ common: dict[str, str] = {}+ if quality["mode"] == "constant-quality":+ common["crf"] = "0"+ if codec == "H.264":+ return _EncoderSettings(+ "libx264", "libx264", "yuv420p", FORMAT_NV12,+ {"preset": "slow", **common}, bit_rate, quality)+ if codec in {"H.265", "HEVC"}:+ values = {"preset": "slow", **common}+ if options.hdr_enabled:+ colors = {"color_space": "bt2020nc", "color_transfer": "smpte2084",+ "color_primaries": "bt2020", "hdr": True}+ hdr_parameters = _x265_hdr_params(colors)+ if hdr_parameters:+ values["x265-params"] = hdr_parameters+ return _EncoderSettings(+ "libx265", "libx265", "yuv420p10le" if ten_bit else "yuv420p",+ FORMAT_P010 if ten_bit else FORMAT_NV12, values, bit_rate, quality)+ if codec == "AV1":+ encoder = "libsvtav1" if _codec_available("libsvtav1") else "libaom-av1"+ if not _codec_available(encoder):+ raise RuntimeError(+ "AV1 CPU encoding is unavailable: neither libsvtav1 nor libaom-av1 can initialize.")+ values = ({"preset": "6"} if encoder == "libsvtav1" else {"cpu-used": "4"})+ values.update(common)+ if encoder == "libaom-av1" and quality["mode"] == "constant-quality":+ values["b"] = "0"+ return _EncoderSettings(+ encoder, encoder, "yuv420p10le" if ten_bit else "yuv420p",+ FORMAT_P010 if ten_bit else FORMAT_NV12, values, bit_rate, quality)+ if codec == "ProRes Proxy":+ values = {"profile": "0"}+ if quality.get("bits_per_mb") is not None:+ values["bits_per_mb"] = str(int(quality["bits_per_mb"]))+ return _EncoderSettings(+ "prores_ks", "prores_ks (Proxy)", "yuv422p10le",+ FORMAT_YUV422P10, values, 0, quality)+ if codec == "ProRes HQ":+ return _EncoderSettings(+ "prores_ks", "prores_ks (HQ)", "yuv422p10le",+ FORMAT_YUV422P10, {"profile": "3"}, 0, quality)+ if codec == "FFV1 Lossless RGB 10-bit":+ return _EncoderSettings(+ "ffv1", "ffv1 (Lossless RGB 10-bit)", "gbrp10le", FORMAT_YUV422P10,+ {"level": "3", "slicecrc": "1"}, 0, quality)+ raise ValueError(f"The in-process host pipeline does not support codec {options.codec!r}.")+++@dataclass(slots=True)+class _PinnedSlot:+ owner: "_PinnedFramePool"+ pointer: int+ plane_pointers: tuple[int, ...]+ strides: tuple[int, ...]+ rows: tuple[int, ...]+ row_bytes: tuple[int, ...]+ held: bool = False+ pts: int | None = None+ duration: int | None = None+ time_base: Fraction | None = None++ def release(self) -> None:+ with self.owner.condition:+ if self.held:+ self.held = False+ self.owner.condition.notify_all()++ def to_av_frame(self) -> tuple[av.VideoFrame, float]:+ tick = time.perf_counter()+ try:+ frame = av.VideoFrame(self.owner.width, self.owner.height, self.owner.pixel_format)+ for index, plane in enumerate(frame.planes):+ source = self.plane_pointers[index]+ source_stride = self.strides[index]+ count = self.row_bytes[index]+ rows = self.rows[index]+ destination = int(plane.buffer_ptr)+ destination_stride = int(plane.line_size)+ if count == source_stride == destination_stride:+ ctypes.memmove(destination, source, count * rows)+ else:+ for row in range(rows):+ ctypes.memmove(destination + row * destination_stride,+ source + row * source_stride, count)+ frame.pts, frame.time_base = self.pts, self.time_base+ if self.duration is not None:+ frame.duration = self.duration+ return frame, time.perf_counter() - tick+ finally:+ self.release()+++class _PinnedFramePool:+ """Four preallocated page-locked frames shared by RTX and encoder stages."""++ def __init__(self, ordinal: int, width: int, height: int, native_format: int,+ pixel_format: str, controller: Any, *, capacity: int = 4,+ timeout: float = 180.0) -> None:+ self.api = _CudaApi()+ self.ordinal, self.width, self.height = int(ordinal), int(width), int(height)+ self.native_format, self.pixel_format = int(native_format), str(pixel_format)+ self.controller, self.capacity, self.timeout = controller, int(capacity), float(timeout)+ self.condition = threading.Condition()+ self.pool_waits = 0+ self.closed = False+ self.device = self.api.device(self.ordinal)+ self.context = self.api.primary_context(self.device)+ if native_format == FORMAT_NV12:+ strides = (width, width)+ rows = (height, (height + 1) // 2)+ row_bytes = strides+ elif native_format == FORMAT_P010:+ strides = (width * 2, width * 2)+ rows = (height, (height + 1) // 2)+ row_bytes = strides+ elif native_format == FORMAT_YUV422P10:+ strides = (width * 2, ((width + 1) // 2) * 2, ((width + 1) // 2) * 2)+ rows = (height, height, height)+ row_bytes = strides+ else:+ self.api.check(self.api.primary_release(self.device), "cuDevicePrimaryCtxRelease")+ raise ValueError("Unsupported pinned-frame format.")+ self.frame_bytes = sum(stride * count for stride, count in zip(strides, rows))+ self.slots: list[_PinnedSlot] = []+ try:+ with self.api.current(self.context):+ for _ in range(self.capacity):+ allocation = ctypes.c_void_p()+ self.api.check(self.api.cuMemHostAlloc(+ ctypes.byref(allocation), self.frame_bytes, CU_MEMHOSTALLOC_PORTABLE),+ "cuMemHostAlloc(encoder frame)")+ base = int(allocation.value or 0)+ pointers, offset = [], 0+ for stride, count in zip(strides, rows):+ pointers.append(base + offset)+ offset += stride * count+ self.slots.append(_PinnedSlot(+ self, base, tuple(pointers), tuple(strides), tuple(rows),+ tuple(row_bytes)))+ except BaseException:+ self.close(abort=True)+ raise++ def acquire(self) -> _PinnedSlot:+ deadline = time.monotonic() + self.timeout+ with self.condition:+ while True:+ if self.controller.cancel.is_set():+ raise Cancelled("Upscale stopped by user.")+ for slot in self.slots:+ if not slot.held:+ slot.held = True+ return slot+ self.pool_waits += 1+ remaining = deadline - time.monotonic()+ if remaining <= 0:+ raise RuntimeError("Pinned encoder-frame pool remained exhausted.")+ self.condition.wait(timeout=min(0.05, remaining))++ def diagnostics(self) -> dict[str, Any]:+ return {+ "surface_pool_capacity": self.capacity,+ "surface_pool_allocated": len(self.slots),+ "surface_pool_waits": self.pool_waits,+ "bytes_per_surface": self.frame_bytes,+ "allocation": "cuda_page_locked_host",+ }++ def close(self, *, abort: bool = False) -> None:+ if self.closed:+ return+ deadline = time.monotonic() + (2.0 if abort else self.timeout)+ with self.condition:+ while any(slot.held for slot in self.slots):+ remaining = deadline - time.monotonic()+ if remaining <= 0:+ if abort:+ self.closed = True+ return+ raise RuntimeError("Encoder retained pinned frames past shutdown.")+ self.condition.wait(timeout=min(0.05, remaining))+ try:+ with self.api.current(self.context):+ for slot in self.slots:+ if slot.pointer:+ self.api.check(self.api.cuMemFreeHost(ctypes.c_void_p(slot.pointer)),+ "cuMemFreeHost(encoder frame)")+ slot.pointer = 0+ finally:+ self.api.check(self.api.primary_release(self.device), "cuDevicePrimaryCtxRelease")+ self.closed = True+++def convert_video_inprocess_host(+ source: Path,+ options: UpscaleOptions,+ *,+ controller: Any,+ progress: Callable[[float, str], None] | None,+ output_dir: str | os.PathLike[str] | None,+ metadata: dict[str, Any] | None = None,+ capabilities: UpscaleCapabilities | None = None,+) -> UpscaleResult:+ """Run CPU/ProRes encoding without raw frame or NUT subprocess pipes."""+ started = time.perf_counter()+ report_path = app_log.session_path()+ metadata = metadata or inspect_video(source, controller, reject_hdr=True)+ width, height = int(metadata["width"]), int(metadata["height"])+ output_width, output_height, _ = output_size(width, height, options)+ capabilities = capabilities or probe_capabilities(options.ai_gpu_uuid, controller=controller)+ ai_gpu = capabilities.gpu+ ordinal = int(ai_gpu["cuda_ordinal"])+ input_format = 2 if int(metadata["depth"]) > 8 else 1+ ten_bit = bool(+ options.hdr_enabled or+ (input_format == 2 and ffmpeg.hdr_mode_supported(options.codec)) or+ ffmpeg._normalize_codec(options.codec) in {+ "ProRes Proxy", "ProRes HQ", "FFV1 Lossless RGB 10-bit"+ })+ encoder = _encoder_settings(options, output_width, output_height, metadata["rate"], ten_bit)+ preview = options.preview_frames is not None or options.preview_seconds is not None+ stamp = time.strftime("%Y%m%d-%H%M%S") + "-" + uuid.uuid4().hex[:8]+ extension = {"MP4": ".mp4", "MKV": ".mkv", "MOV": ".mov"}[options.container]+ destination = prepare_output_dir(output_dir)+ kind = "RTXVIDEO_PREVIEW" if preview else "RTXVIDEO"+ output = unique_output_path(destination / output_filename(+ source, extension, "Auto" if preview else options.rename_mode,+ options.custom_suffix, f"{source.stem}_{kind}_{stamp}"))+ destination_file = OutputFile(output)+ decoded_container: Any | None = None+ encoded_container: Any | None = None+ session: RTXVideoSession | None = None+ pinned_pool: _PinnedFramePool | None = None+ decode_thread: threading.Thread | None = None+ encode_thread: threading.Thread | None = None+ failures: list[BaseException] = []+ stop, decode_stop = threading.Event(), threading.Event()+ delivered = 0+ decode_backends: set[str] = set()+ timings: dict[str, float] = {+ "decode_seconds": 0.0, "software_prepare_seconds": 0.0,+ "bridge_input_seconds": 0.0, "ngx_seconds": 0.0,+ "bridge_output_seconds": 0.0, "host_copy_seconds": 0.0,+ "encode_seconds": 0.0,+ }++ def update(value: float, message: str) -> None:+ if controller.cancel.is_set():+ raise Cancelled("Upscale stopped by user.")+ if progress:+ progress(max(0.0, min(1.0, value)), message)++ def drain_slots(target: queue.Queue | None) -> None:+ if target is None:+ return+ while True:+ try:+ item = target.get_nowait()+ except queue.Empty:+ return+ if isinstance(item, _PinnedSlot):+ item.release()++ encode_queue: queue.Queue | None = None+ try:+ update(0.01, "Preparing video processing")+ JOBS.mkdir(exist_ok=True)+ job = tempfile.TemporaryDirectory(prefix="rtx-video-host-", dir=JOBS)+ try:+ job_dir = Path(job.name)+ temp_video = job_dir / (+ "encoded.mkv" if encoder.codec == "ffv1" else+ "encoded.mov" if encoder.codec == "prores_ks" else "encoded.mp4"+ )+ decode_device = HWAccel(+ "cuda", device=str(ordinal), allow_software_fallback=True,+ options={"primary_ctx": "1"}, is_hw_owned=True)+ from .media import decode_filter+ normalization, _ = decode_filter(metadata)+ decoded_container = open_video_decoder(source, controller, pixel_format="gbrp10le" if input_format == 2 else "rgba", video_filter=normalization)+ input_stream = decoded_container.streams.video[0]+ input_stream.thread_type = "AUTO"+ decoder_iterator = iter(decoded_container.decode(input_stream))+ tick = time.perf_counter()+ try:+ first_frame = next(decoder_iterator)+ except StopIteration as exc:+ raise ValueError("The input contains no decodable video frames.") from exc+ timings["decode_seconds"] += time.perf_counter() - tick++ encoded_container = VideoOutput(temp_video, controller)+ output_stream = encoded_container.add_stream(encoder.codec, rate=metadata["rate"])+ output_stream.width, output_stream.height = output_width, output_height+ output_stream.pix_fmt = encoder.pixel_format+ stream_tb = input_stream.time_base or Fraction(1, max(1, round(float(metadata["rate"]))))+ output_stream.time_base = stream_tb+ output_stream.codec_context.time_base = stream_tb+ output_stream.codec_context.options = encoder.options+ output_stream.codec_context.bit_rate = encoder.bit_rate+ _set_color_properties(output_stream.codec_context, bool(options.hdr_enabled))+ if encoder.codec == "ffv1":+ output_stream.codec_context.colorspace = 0+ output_stream.codec_context.color_range = 2+ output_stream.codec_context.open()++ session = RTXVideoSession(+ width, height, output_width, output_height, options, input_format,+ capabilities, controller)+ pinned_pool = _PinnedFramePool(+ ordinal, output_width, output_height, encoder.native_format,+ {FORMAT_NV12: "nv12", FORMAT_P010: "p010le",+ FORMAT_YUV422P10: "yuv422p10le"}[encoder.native_format], controller)+ decode_queue: queue.Queue = queue.Queue(maxsize=4)+ encode_queue = queue.Queue(maxsize=4)++ def decode_worker() -> None:+ def put(item: Any) -> bool:+ while not stop.is_set() and not decode_stop.is_set():+ if controller.cancel.is_set() or failures:+ stop.set()+ return False+ try:+ decode_queue.put(item, timeout=0.05)+ return True+ except queue.Full:+ continue+ return False+ try:+ if not put(first_frame):+ return+ while not stop.is_set() and not decode_stop.is_set():+ frame_tick = time.perf_counter()+ try:+ frame = next(decoder_iterator)+ except StopIteration:+ timings["decode_seconds"] += time.perf_counter() - frame_tick+ break+ timings["decode_seconds"] += time.perf_counter() - frame_tick+ if frame.is_corrupt:+ raise RuntimeError("The video decoder returned a corrupt frame.")+ if not put(frame):+ return+ except BaseException as exc:+ failures.append(exc)+ stop.set()+ finally:+ if not decode_stop.is_set():+ put(_END)++ encoded_frames = [0]++ def encode_worker() -> None:+ try:+ while not stop.is_set():+ item = _get_bounded(encode_queue, stop, controller, failures)+ if item is _END:+ break+ encode_tick = time.perf_counter()+ frame, copy_seconds = item.to_av_frame()+ timings["host_copy_seconds"] += copy_seconds+ for packet in output_stream.encode(frame):+ encoded_container.mux(packet)+ timings["encode_seconds"] += time.perf_counter() - encode_tick+ encoded_frames[0] += 1+ del item, frame+ if not failures and not controller.cancel.is_set():+ encode_tick = time.perf_counter()+ for packet in output_stream.encode():+ encoded_container.mux(packet)+ timings["encode_seconds"] += time.perf_counter() - encode_tick+ except BaseException as exc:+ failures.append(exc)+ stop.set()++ decode_thread = threading.Thread(target=decode_worker, name="rtx-host-decoder", daemon=True)+ encode_thread = threading.Thread(target=encode_worker, name="rtx-host-encoder", daemon=True)+ pipeline_started = time.perf_counter()+ decode_thread.start()+ encode_thread.start()++ default_duration = max(1, round(Fraction(1, 1) / metadata["rate"] / stream_tb))+ origin_pts = round(Fraction(str(metadata["origin"])) / stream_tb)+ first_time: Fraction | None = None+ preview_origin: int | None = None+ last_pts: int | None = None+ timestamp_fallbacks = 0+ stopped_early = False+ source_dimensions = (int(first_frame.width), int(first_frame.height))+ estimated = int(metadata["frames"] or max(+ 1, math.ceil(metadata["duration"] * float(metadata["rate"]))))+ if options.preview_frames is not None:+ estimated = min(estimated, int(options.preview_frames))+ elif options.preview_seconds is not None:+ estimated = min(estimated, max(+ 1, math.ceil(options.preview_seconds * float(metadata["rate"]))))+ last_update = 0.0+ while True:+ frame = _get_bounded(decode_queue, stop, controller, failures)+ if frame is _END:+ break+ if (int(frame.width), int(frame.height)) != source_dimensions:+ raise ValueError("Source dimensions changed during decoding.")+ pts, duration, used_fallback = normalize_frame_timing(+ frame_pts=frame.pts, frame_duration=frame.duration,+ frame_time_base=frame.time_base, stream_time_base=stream_tb,+ origin_pts=origin_pts, delivered=delivered,+ default_duration=default_duration, last_pts=last_pts)+ timestamp_fallbacks += int(used_fallback)+ timestamp = Fraction(pts) * stream_tb+ if first_time is None:+ first_time = timestamp+ if ((options.preview_frames is not None and delivered >= int(options.preview_frames)) or+ (options.preview_seconds is not None and delivered and+ float(timestamp - first_time) >= float(options.preview_seconds))):+ stopped_early = True+ decode_stop.set()+ del frame+ break+ slot = pinned_pool.acquire()+ try:+ if frame.format.name == "cuda":+ decode_backends.add("nvdec")+ detail = session.process_cuda_to_host_planar(+ frame, output_format=encoder.native_format,+ plane_pointers=slot.plane_pointers, strides=slot.strides,+ color_matrix=_matrix_code(metadata), color_range=_range_code(metadata),+ color_primaries=_primaries_code(metadata),+ color_transfer=_transfer_code(metadata),+ chroma_location=_chroma_location_code(metadata),+ rotation=int(metadata["rotation"]))+ else:+ decode_backends.add("ffmpeg-vulkan")+ prepare_tick = time.perf_counter()+ packed = packed_bytes(frame)+ timings["software_prepare_seconds"] += time.perf_counter() - prepare_tick+ detail = session.process_host_to_host_planar(+ packed, output_format=encoder.native_format,+ plane_pointers=slot.plane_pointers, strides=slot.strides)+ timings["bridge_input_seconds"] += detail["input_ms"] / 1000.0+ timings["ngx_seconds"] += detail["ngx_ms"] / 1000.0+ timings["bridge_output_seconds"] += detail["output_ms"] / 1000.0+ if preview:+ if preview_origin is None:+ preview_origin = pts+ slot.pts = pts - preview_origin+ else:+ slot.pts = pts+ slot.time_base, slot.duration = stream_tb, duration+ if not _put_bounded(encode_queue, slot, stop, controller, failures):+ raise failures[0] if failures else Cancelled("Upscale stopped by user.")+ except BaseException:+ slot.release()+ raise+ delivered += 1+ last_pts = pts+ del frame, slot+ now = time.perf_counter()+ if now - last_update > 0.2:+ update(+ min(0.87, 0.05 + 0.82 * delivered / max(1, estimated)),+ f"Upscaling video: {delivered:,} / {estimated:,} frames")+ last_update = now+ if not delivered:+ raise ValueError("The input contains no decodable video frames.")+ _put_bounded(encode_queue, _END, threading.Event(), controller, failures)+ decode_thread.join(timeout=30)+ encode_thread.join(timeout=600)+ if decode_thread.is_alive() or encode_thread.is_alive():+ raise RuntimeError("The bounded host-encoding pipeline did not drain cleanly.")+ timings["pipeline_seconds"] = time.perf_counter() - pipeline_started+ if failures:+ raise failures[0]+ if encoded_frames[0] != delivered:+ raise RuntimeError(f"The encoder accepted {encoded_frames[0]} frames instead of {delivered}.")+ actual_encoder = encoded_container.actual_encoder+ encoded_container.close()+ encoded_container = None+ decoded_container.close()+ decoded_container = None+ gc.collect()+ pool_status = pinned_pool.diagnostics()+ pinned_pool.close()+ pinned_pool = None+ session_status = session.structured_status(+ decode_backend="+".join(sorted(decode_backends)) or "unknown",+ encode_backend=actual_encoder)+ session.close()+ if session.completed_frames != delivered:+ raise RuntimeError("RTX Video bridge completion does not match frame accounting.")+ if not preview and (not metadata["frames"] or delivered != metadata["frames"]):+ exact = ffmpeg.probe_video(source, count_mode="exact", strict_decode=True,+ controller=controller)+ if int(exact["frames"]) != delivered:+ raise RuntimeError(+ f"Source has {exact['frames']} frames but only {delivered} were processed.")+ update(0.90, "Muxing original audio, subtitles, chapters, and metadata")+ mux_tick = time.perf_counter()+ audio_diagnostics: dict = {}+ ffmpeg.final_mux(+ temp_video, source, destination_file.temporary, options.container, controller,+ preserve_supported_subtitles=True, source_time_origin=metadata["origin"],+ audio_diagnostics=audio_diagnostics)+ timings["final_mux_seconds"] = time.perf_counter() - mux_tick+ update(0.96, "Verifying output frames, resolution, chroma, and HDR signaling")+ verified = ffmpeg.probe_video(destination_file.temporary, count_mode="packets",+ controller=controller)+ if int(verified["frames"]) != delivered:+ verified = ffmpeg.probe_video(+ destination_file.temporary, count_mode="exact", strict_decode=True,+ controller=controller)+ if (int(verified["frames"]) != delivered or+ (int(verified["width"]), int(verified["height"])) !=+ (output_width, output_height)):+ raise RuntimeError("Saved output does not match processed frame count or dimensions.")+ saved = inspect_video(destination_file.temporary, controller)+ if encoder.codec == "prores_ks" and saved["stream"].get("pix_fmt") != "yuv422p10le":+ raise RuntimeError("ProRes output did not preserve direct 10-bit 4:2:2 chroma.")+ expected = {+ "ProRes HQ": ("prores", "yuv422p10le", 10),+ "FFV1 Lossless RGB 10-bit": ("ffv1", "gbrp10le", 10),+ }.get(ffmpeg._normalize_codec(options.codec))+ if expected and (saved["stream"].get("codec_name"), saved["stream"].get("pix_fmt"),+ int(saved["depth"])) != expected:+ raise RuntimeError(f"Saved output does not match {options.codec}.")+ if options.hdr_enabled and (+ saved["depth"] < 10 or not saved["hdr"] or+ saved["stream"].get("color_primaries") != "bt2020" or+ saved["stream"].get("color_space") != (+ "gbr" if encoder.codec == "ffv1" else "bt2020nc")):+ raise RuntimeError("Saved file failed HDR color and bit-depth verification.")+ if not options.hdr_enabled and saved["hdr"]:+ raise RuntimeError("SDR output unexpectedly contains HDR signaling.")+ if controller.cancel.is_set():+ raise Cancelled("Upscale stopped by user.")+ elapsed = time.perf_counter() - started+ throughput = delivered / max(timings["pipeline_seconds"], 1e-9)+ bridge_seconds = (timings["bridge_input_seconds"] + timings["ngx_seconds"] ++ timings["bridge_output_seconds"])+ stage_ms = {+ "decode_ms": timings["decode_seconds"] * 1000 / delivered,+ "bridge_ms": bridge_seconds * 1000 / delivered,+ "encode_ms": timings["encode_seconds"] * 1000 / delivered,+ }+ slowest_ms = max(stage_ms.values())+ ceiling_fps = 1000.0 / slowest_ms if slowest_ms else 0.0+ timings.update(+ steady_state_fps=throughput,+ slowest_stage_ceiling_fps=ceiling_fps,+ ceiling_utilization=throughput / ceiling_fps if ceiling_fps else 0.0,+ timestamp_fallbacks=timestamp_fallbacks)+ memory_path = (+ "cuda_to_pinned_host"+ if decode_backends == {"nvdec"}+ else "host_upload_cuda_to_pinned_host"+ )+ session_status["timings"] = dict(timings)+ session_status["memory_path"] = memory_path+ session_status["pinned_pool"] = pool_status+ session_status["adapters"] = {"ai": ai_gpu, "decode": ai_gpu, "encode": actual_encoder}+ session_status["audio_streams"] = audio_diagnostics.get("streams", [])+ destination_file.publish()+ app_log.info(+ "upscale-host", f"done src={source.name} out={output.name} frames={delivered} "+ f"elapsed={elapsed:.2f}s fps={delivered / max(elapsed, 1e-9):.1f} "+ f"encoder={actual_encoder}")+ update(1.0, "Complete — in-process pinned RTX Video path confirmed")+ return UpscaleResult(+ str(output), report_path, delivered, output_width, output_height,+ options.hdr_enabled, elapsed,+ bridge_version=str(capabilities.bridge_version),+ memory_path=memory_path,+ decode_backend="+".join(sorted(decode_backends)) or "unknown",+ encode_backend=actual_encoder, timings=timings,+ bridge_status=session_status)+ finally:+ job.cleanup()+ except BaseException:+ stop.set()+ decode_stop.set()+ for thread in (decode_thread, encode_thread):+ if thread is not None:+ thread.join(timeout=2)+ drain_slots(encode_queue)+ if encoded_container is not None:+ with suppress(Exception):+ encoded_container.close()+ if decoded_container is not None:+ with suppress(Exception):+ decoded_container.close()+ if session is not None and not session.closed:+ with suppress(Exception):+ session.close(abort=True)+ if pinned_pool is not None and not pinned_pool.closed:+ with suppress(Exception):+ pinned_pool.close(abort=True)+ destination_file.cleanup(rollback=True)+ raisediff --git a/src/upscale/video/media.py b/src/upscale/video/media.pyindex bca3676..96a2c98 100644--- a/src/upscale/video/media.py+++ b/src/upscale/video/media.py@@ -1,219 +1,269 @@-from __future__ import annotations--import math-import subprocess-import threading-from contextlib import suppress-from fractions import Fraction-from pathlib import Path--import av-import numpy as np--from ...core import app_log-from ...core.ffmpeg.probe import _run_json-from ...core.jobs import BoundedLogBuffer, Cancelled, drain_bounded_text-from ...core.paths import FFMPEG, FFPROBE--HDR_TAGS = {"smpte2084", "arib-std-b67"}---def positive_fraction(value, default=Fraction(1)):- try:- result = Fraction(str(value).replace(":", "/"))- return result if result > 0 else default- except (ValueError, ZeroDivisionError):- return default---class PipeReader:- """Do not expose the Windows pipe's unusable seek method to libavformat."""- def __init__(self, stream):- self.stream = stream-- def read(self, size):- return self.stream.read(size)---class PipeWriter:- def __init__(self, stream):- self.stream = stream-- def write(self, data):- view = memoryview(data)- size = len(view)- while view:- n = self.stream.write(view)- if not n:- raise BrokenPipeError("Encoder pipe closed.")- view = view[n:]- return size-- def flush(self):- self.stream.flush()--+from __future__ import annotations++import math+import subprocess+from ...core.ffmpeg.vulkan import prepare_command+import threading+from contextlib import suppress+from fractions import Fraction+from pathlib import Path++import av+import numpy as np++from ...core import app_log+from ...core.ffmpeg.probe import _run_json+from ...core.jobs import BoundedLogBuffer, Cancelled, drain_bounded_text+from ...core.paths import FFMPEG, FFPROBE++HDR_TAGS = {"smpte2084", "arib-std-b67"}+++def positive_fraction(value, default=Fraction(1)):+ try:+ result = Fraction(str(value).replace(":", "/"))+ return result if result > 0 else default+ except (ValueError, ZeroDivisionError):+ return default+++class PipeReader:+ """Do not expose the Windows pipe's unusable seek method to libavformat."""+ def __init__(self, stream):+ self.stream = stream++ def read(self, size):+ return self.stream.read(size)+++class PipeWriter:+ def __init__(self, stream):+ self.stream = stream++ def write(self, data):+ view = memoryview(data)+ size = len(view)+ while view:+ n = self.stream.write(view)+ if not n:+ raise BrokenPipeError("Encoder pipe closed.")+ view = view[n:]+ return size++ def flush(self):+ self.stream.flush()++def inspect_video(path: Path, controller=None, *, reject_hdr=False) -> dict:- data = _run_json([str(FFPROBE), "-v", "error", "-select_streams", "v:0", "-show_streams",- "-show_format", "-of", "json", str(path)], controller=controller)- streams = data.get("streams") or []- if not streams:- raise ValueError("The selected file contains no video stream.")- stream = streams[0]- side = stream.get("side_data_list") or []- hdr = stream.get("color_transfer") in HDR_TAGS or any("dovi" in str(s).lower() or "dolby vision" in str(s).lower() for s in side)- if reject_hdr and hdr:- raise ValueError("Existing HDR input is not supported by Upscale. Supply SDR footage; RTX Video HDR converts SDR to new HDR.")- width, height = int(stream["width"]), int(stream["height"])- rotation = int(next((s["rotation"] for s in side if "rotation" in s), (stream.get("tags") or {}).get("rotate", 0))) % 360- if rotation not in (0, 90, 180, 270):- raise ValueError("Upscale supports rotation metadata in multiples of 90 degrees.")- raw_sar = stream.get("sample_aspect_ratio", "1:1")- sar = positive_fraction(raw_sar)- if rotation in (90, 270):- width, height, sar = height, width, 1 / sar- pixel_format = stream.get("pix_fmt", "yuv420p")- depth = max(c.bits for c in av.VideoFormat(pixel_format).components)- rate = positive_fraction(stream.get("avg_frame_rate"),- positive_fraction(stream.get("r_frame_rate"), Fraction(30)))- origin = float(data.get("format", {}).get("start_time") or stream.get("start_time") or 0)- return {"stream": stream, "hdr": hdr, "depth": depth, "rotation": rotation,- "source_width": width, "source_height": height, "sar": sar,- "width": math.ceil(width * sar / 2) * 2, "height": math.ceil(height / 2) * 2,- "rate": rate, "duration": float(data.get("format", {}).get("duration") or stream.get("duration") or 0),+ data = _run_json([str(FFPROBE), "-v", "error", "-select_streams", "v:0", "-show_streams",+ "-show_format", "-of", "json", str(path)], controller=controller)+ streams = data.get("streams") or []+ if not streams:+ raise ValueError("The selected file contains no video stream.")+ stream = streams[0]+ side = stream.get("side_data_list") or []+ hdr = stream.get("color_transfer") in HDR_TAGS or any("dovi" in str(s).lower() or "dolby vision" in str(s).lower() for s in side)+ if reject_hdr and hdr:+ raise ValueError("Existing HDR input is not supported by Upscale. Supply SDR footage; RTX Video HDR converts SDR to new HDR.")+ width, height = int(stream["width"]), int(stream["height"])+ rotation = int(next((s["rotation"] for s in side if "rotation" in s), (stream.get("tags") or {}).get("rotate", 0))) % 360+ if rotation not in (0, 90, 180, 270):+ raise ValueError("Upscale supports rotation metadata in multiples of 90 degrees.")+ raw_sar = stream.get("sample_aspect_ratio", "1:1")+ sar = positive_fraction(raw_sar)+ if rotation in (90, 270):+ width, height, sar = height, width, 1 / sar+ pixel_format = stream.get("pix_fmt", "yuv420p")+ depth = max(c.bits for c in av.VideoFormat(pixel_format).components)+ rate = positive_fraction(stream.get("avg_frame_rate"),+ positive_fraction(stream.get("r_frame_rate"), Fraction(30)))+ origin = float(data.get("format", {}).get("start_time") or stream.get("start_time") or 0)+ return {"stream": stream, "hdr": hdr, "depth": depth, "rotation": rotation,+ "source_width": width, "source_height": height, "sar": sar,+ "width": math.ceil(width * sar / 2) * 2, "height": math.ceil(height / 2) * 2,+ "rate": rate, "duration": float(data.get("format", {}).get("duration") or stream.get("duration") or 0),"origin": origin, "frames": int(stream.get("nb_frames") or 0) if str(stream.get("nb_frames", "0")).isdigit() else 0}-def decode_filter(meta: dict) -> tuple[str, list[str]]:- s = meta["stream"]- sd = int(s["height"]) <= 576- fallback = "bt470bg" if int(s["height"]) == 576 else "smpte170m" if sd else "bt709"- assumptions = []- def color(key, default):- v = s.get(key)- if not v or v in ("unknown", "unspecified", "reserved"):- assumptions.append(f"Unspecified {key}: assumed {default}.")- return default- return v- matrix = color("color_space", "gbr" if av.VideoFormat(s.get("pix_fmt", "yuv420p")).is_rgb else fallback)- primaries = color("color_primaries", fallback)- transfer = color("color_transfer", "bt709")- range_in = "full" if s.get("color_range") == "pc" or av.VideoFormat(s.get("pix_fmt", "yuv420p")).is_rgb else "limited"- planar = "gbrp10le" if meta["depth"] > 8 else "gbrp"- # Planar 10-bit has a stable NUT tag across bundled FFmpeg/PyAV versions.- # Some releases disagree on the packed x2bgr10 tag (decoded as rgb555).- packed = "gbrp10le" if meta["depth"] > 8 else "rgba"- filters = [f"zscale=matrixin={matrix}:primariesin={primaries}:transferin={transfer}:rangein={range_in}:matrix=gbr:primaries=bt709:transfer=bt470m:range=full", f"format={planar}"]- if meta["rotation"] == 90:- filters.append("transpose=cclock")- elif meta["rotation"] == 270:- filters.append("transpose=clock")- elif meta["rotation"] == 180:- filters += ["hflip", "vflip"]- filters += [f"scale={meta['width']}:{meta['height']}:flags=lanczos", "setsar=1", f"format={packed}", f"setpts=PTS-({meta['origin']:.9f})/TB"]- if meta["depth"] > 10:- assumptions.append("Source precision converted to the SDK's supported 10-bit RGB input.")- return ",".join(filters), assumptions---def output_filter(pixel_format: int, hdr: bool) -> str:- planar = {1: "gbrp", 2: "gbrp10le", 3: "gbrpf32le"}[pixel_format]- pin = "bt2020" if hdr and pixel_format == 2 else "bt709"- tin = "linear" if pixel_format == 3 else "smpte2084" if hdr else "bt470m"- pout, tout, matrix = ("bt2020", "smpte2084", "bt2020nc") if hdr else ("bt709", "bt709", "bt709")- return (f"format={planar},zscale=matrixin=gbr:primariesin={pin}:transferin={tin}:rangein=full:"- f"matrix={matrix}:primaries={pout}:transfer={tout}:range=limited" + (":npl=80" if pixel_format == 3 else ""))---def start_decoder(source, meta, controller):- vf, assumptions = decode_filter(meta)- command = [str(FFMPEG), "-hide_banner", "-v", "warning", "-xerror", "-copyts", "-noautorotate", "-i", str(source),- "-map", "0:v:0", "-an", "-sn", "-dn", "-vf", vf, "-c:v", "rawvideo", "-pix_fmt",- "gbrp10le" if meta["depth"] > 8 else "rgba", "-fps_mode", "passthrough", "-enc_time_base", "demux",- "-f", "nut", "pipe:1"]- process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, creationflags=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)- thread.start()- return process, thread, logs, assumptions+def sdr_normalization_filter(matrix: str, primaries: str, transfer: str, range_in: str) -> str:+ """Convert to the SDK's pure gamma-2.2 RGB without display black scaling.+ libplacebo's BT.1886 conversion assumes a display black point. RTX's CUDA+ output conversion, like zscale, uses ideal gamma 2.4 for BT.709. Decode+ the source curve explicitly before libplacebo handles the gamut/matrix;+ otherwise the two conversions lift shadows even with TrueHDR disabled.+ MAIN runs on nonlinear RGB after YUV decoding, before gamut conversion.+ """+ from ...core.ffmpeg.filters import shader_filter+ srgb_curve = ("vec3 linear = mix(pow((v + 0.055) / 1.055, vec3(2.4)), "+ "v / 12.92, lessThanEqual(v, vec3(0.04045))); "+ "return pow(linear, vec3(1.0 / 2.2));")+ curve = {+ "bt470m": "return v;", "gamma22": "return v;",+ "bt470bg": "return pow(v, vec3(2.8 / 2.2));",+ "gamma28": "return pow(v, vec3(2.8 / 2.2));",+ "linear": "return pow(v, vec3(1.0 / 2.2));",+ "iec61966-2-1": srgb_curve, "srgb": srgb_curve,+ }.get(transfer)+ if curve is None:+ if transfer in {"bt709", "smpte170m", "smpte240m", "bt2020-10", "bt2020-12",+ "iec61966-2-4", "bt1361e"}:+ curve = "return pow(v, vec3(2.4 / 2.2));"+ else:+ # Preserve the existing library conversion for less common curves+ # (e.g. logarithmic footage), rather than assume they are BT.709.+ return (f"zscale=matrixin={matrix}:primariesin={primaries}:transferin={transfer}:rangein={range_in}:"+ "matrix=gbr:primaries=bt709:transfer=bt470m:range=full")+ shader = """//!HOOK MAIN+//!BIND HOOKED+vec3 rtx_gamma22(vec3 v) {+ v = max(v, vec3(0.0));+ %s+}+vec4 hook() {+ vec4 pixel = HOOKED_tex(HOOKED_pos);+ return vec4(rtx_gamma22(pixel.rgb), pixel.a);+}+""" % curve+ # The shader supplies the transfer conversion. Equal gamma-2.2 tags keep+ # the renderer from adding a second conversion or a display black offset.+ tags = f"setparams=colorspace={matrix}:color_primaries={primaries}:color_trc=bt470m:range={range_in}"+ conversion = shader_filter(shader, options="format=gbrp16le:colorspace=0:color_primaries=bt709:"+ "color_trc=bt470m:range=pc:gamut_mode=clip")+ return tags + "," + conversion-def packed_bytes(frame: av.VideoFrame) -> np.ndarray:- if frame.format.name == "gbrp10le":- channels = [np.frombuffer(p, dtype="<u2").reshape(frame.height, p.line_size // 2)[:, :frame.width].astype(np.uint32)- for p in frame.planes]- g,b,r = channels- return np.ascontiguousarray(r | (g << 10) | (b << 20) | np.uint32(3 << 30))- if frame.format.name != "rgba":- raise RuntimeError(f"Unexpected decoder pixel format {frame.format.name}; expected rgba or gbrp10le.")- p = frame.planes[0]- return np.ascontiguousarray(np.frombuffer(p, dtype=np.uint8).reshape(frame.height, p.line_size)[:, :frame.width * 4])--def result_frame(data, width, height, pixel_format):- if pixel_format == 2:- packed = np.frombuffer(data, dtype="<u4").reshape(height, width)- out = av.VideoFrame(width, height, "gbrp10le")- for plane, shift in zip(out.planes, (10, 20, 0)):- padded = np.zeros((height, plane.line_size // 2), dtype="<u2")- padded[:, :width] = (packed >> shift) & 1023- plane.update(padded)- return out- if pixel_format == 3:- rgba = np.frombuffer(data, dtype="<f2").reshape(height, width, 4).astype(np.float32)- if not np.isfinite(rgba[:, :, :3]).all():- raise RuntimeError("RTX Video HDR returned non-finite pixels.")- out = av.VideoFrame(width, height, "gbrpf32le")- for plane, channel in zip(out.planes, (1, 2, 0)):- padded = np.zeros((height, plane.line_size // 4), dtype="<f4")- padded[:, :width] = rgba[:, :, channel]- plane.update(padded)- return out- out = av.VideoFrame(width, height, "rgba")- p = out.planes[0]- raw = np.frombuffer(data, dtype=np.uint8).reshape(height, width * 4)- if p.line_size == width * 4:- p.update(raw)- else:- padded = np.zeros((height, p.line_size), dtype=np.uint8)- padded[:, :width * 4] = raw- p.update(padded)- return out---def finish_process(process, thread, logs, controller, *, expected_stop=False):- try:- if expected_stop and process.poll() is None:- process.terminate()- process.wait(timeout=120)- thread.join(timeout=2)- if controller.cancel.is_set():- raise Cancelled("Upscale stopped by user.")- if process.returncode and not expected_stop:- detail = logs.snapshot() if hasattr(logs, "snapshot") else logs[-60:]- app_log.error("ffmpeg", "video subprocess failed", "\n".join(detail)[-500:])- raise RuntimeError("Video subprocess failed:\n" + "\n".join(detail))- finally:- controller.unregister(process)---def close_process(process, controller, thread=None):- """Reap before deleting the job directory, including failed/partial encodes."""- try:- if process.poll() is None:- with suppress(OSError):- process.terminate()- try:- process.wait(timeout=5)- except subprocess.TimeoutExpired:- process.kill()- process.wait(timeout=5)- finally:- controller.unregister(process)- if thread is not None:- thread.join(timeout=2)- for stream in (process.stdin, process.stdout, process.stderr):- if stream:- with suppress(OSError):- stream.close()+def decode_filter(meta: dict) -> tuple[str, list[str]]:+ s = meta["stream"]+ sd = int(s["height"]) <= 576+ fallback = "bt470bg" if int(s["height"]) == 576 else "smpte170m" if sd else "bt709"+ assumptions = []+ def color(key, default):+ v = s.get(key)+ if not v or v in ("unknown", "unspecified", "reserved"):+ assumptions.append(f"Unspecified {key}: assumed {default}.")+ return default+ return v+ matrix = color("color_space", "gbr" if av.VideoFormat(s.get("pix_fmt", "yuv420p")).is_rgb else fallback)+ primaries = color("color_primaries", fallback)+ transfer = color("color_transfer", "bt709")+ range_in = "full" if s.get("color_range") == "pc" or av.VideoFormat(s.get("pix_fmt", "yuv420p")).is_rgb else "limited"+ planar = "gbrp10le" if meta["depth"] > 8 else "gbrp"+ # Planar 10-bit has a stable NUT tag across bundled FFmpeg/PyAV versions.+ # Some releases disagree on the packed x2bgr10 tag (decoded as rgb555).+ packed = "gbrp10le" if meta["depth"] > 8 else "rgba"+ filters = [sdr_normalization_filter(matrix, primaries, transfer, range_in), f"format={planar}"]+ if meta["rotation"] == 90:+ filters.append("transpose=cclock")+ elif meta["rotation"] == 270:+ filters.append("transpose=clock")+ elif meta["rotation"] == 180:+ filters += ["hflip", "vflip"]+ filters += [f"scale={meta['width']}:{meta['height']}:flags=lanczos", "setsar=1", f"format={packed}", f"setpts=PTS-({meta['origin']:.9f})/TB"]+ if meta["depth"] > 10:+ assumptions.append("Source precision converted to the SDK's supported 10-bit RGB input.")+ return ",".join(filters), assumptions+++def output_filter(pixel_format: int, hdr: bool) -> str:+ planar = {1: "gbrp", 2: "gbrp10le", 3: "gbrpf32le"}[pixel_format]+ pin = "bt2020" if hdr and pixel_format == 2 else "bt709"+ tin = "linear" if pixel_format == 3 else "smpte2084" if hdr else "bt470m"+ pout, tout, matrix = ("bt2020", "smpte2084", "bt2020nc") if hdr else ("bt709", "bt709", "bt709")+ return (f"format={planar},zscale=matrixin=gbr:primariesin={pin}:transferin={tin}:rangein=full:"+ f"matrix={matrix}:primaries={pout}:transfer={tout}:range=limited" + (":npl=80" if pixel_format == 3 else ""))+++def start_decoder(source, meta, controller):+ vf, assumptions = decode_filter(meta)+ command = [str(FFMPEG), "-hide_banner", "-v", "warning", "-xerror", "-copyts", "-noautorotate", "-i", str(source),+ "-map", "0:v:0", "-an", "-sn", "-dn", "-vf", vf, "-c:v", "rawvideo", "-pix_fmt",+ "gbrp10le" if meta["depth"] > 8 else "rgba", "-fps_mode", "passthrough", "-enc_time_base", "demux",+ "-f", "nut", "pipe:1"]+ command = prepare_command(command)+ 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)+ thread.start()+ return process, thread, logs, assumptions+++def packed_bytes(frame: av.VideoFrame) -> np.ndarray:+ if frame.format.name == "gbrp10le":+ channels = [np.frombuffer(p, dtype="<u2").reshape(frame.height, p.line_size // 2)[:, :frame.width].astype(np.uint32)+ for p in frame.planes]+ g,b,r = channels+ return np.ascontiguousarray(r | (g << 10) | (b << 20) | np.uint32(3 << 30))+ if frame.format.name != "rgba":+ raise RuntimeError(f"Unexpected decoder pixel format {frame.format.name}; expected rgba or gbrp10le.")+ p = frame.planes[0]+ return np.ascontiguousarray(np.frombuffer(p, dtype=np.uint8).reshape(frame.height, p.line_size)[:, :frame.width * 4])+++def result_frame(data, width, height, pixel_format):+ if pixel_format == 2:+ packed = np.frombuffer(data, dtype="<u4").reshape(height, width)+ out = av.VideoFrame(width, height, "gbrp10le")+ for plane, shift in zip(out.planes, (10, 20, 0)):+ padded = np.zeros((height, plane.line_size // 2), dtype="<u2")+ padded[:, :width] = (packed >> shift) & 1023+ plane.update(padded)+ return out+ if pixel_format == 3:+ rgba = np.frombuffer(data, dtype="<f2").reshape(height, width, 4).astype(np.float32)+ if not np.isfinite(rgba[:, :, :3]).all():+ raise RuntimeError("RTX Video HDR returned non-finite pixels.")+ out = av.VideoFrame(width, height, "gbrpf32le")+ for plane, channel in zip(out.planes, (1, 2, 0)):+ padded = np.zeros((height, plane.line_size // 4), dtype="<f4")+ padded[:, :width] = rgba[:, :, channel]+ plane.update(padded)+ return out+ out = av.VideoFrame(width, height, "rgba")+ p = out.planes[0]+ raw = np.frombuffer(data, dtype=np.uint8).reshape(height, width * 4)+ if p.line_size == width * 4:+ p.update(raw)+ else:+ padded = np.zeros((height, p.line_size), dtype=np.uint8)+ padded[:, :width * 4] = raw+ p.update(padded)+ return out+++def finish_process(process, thread, logs, controller, *, expected_stop=False):+ try:+ if expected_stop and process.poll() is None:+ process.terminate()+ process.wait(timeout=120)+ thread.join(timeout=2)+ if controller.cancel.is_set():+ raise Cancelled("Upscale stopped by user.")+ if process.returncode and not expected_stop:+ detail = logs.snapshot() if hasattr(logs, "snapshot") else logs[-60:]+ app_log.error("ffmpeg", "video subprocess failed", "\n".join(detail)[-500:])+ raise RuntimeError("Video subprocess failed:\n" + "\n".join(detail))+ finally:+ controller.unregister(process)+++def close_process(process, controller, thread=None):+ """Reap before deleting the job directory, including failed/partial encodes."""+ try:+ if process.poll() is None:+ with suppress(OSError):+ process.terminate()+ try:+ process.wait(timeout=5)+ except subprocess.TimeoutExpired:+ process.kill()+ process.wait(timeout=5)+ finally:+ controller.unregister(process)+ if thread is not None:+ thread.join(timeout=2)+ for stream in (process.stdin, process.stdout, process.stderr):+ if stream:+ with suppress(OSError):+ stream.close()diff --git a/src/upscale/video/models.py b/src/upscale/video/models.pyindex adaebd1..4cda0e6 100644--- a/src/upscale/video/models.py+++ b/src/upscale/video/models.py@@ -1,175 +1,175 @@-from __future__ import annotations--import math-from dataclasses import dataclass, field, fields-from fractions import Fraction--from ...core.ffmpeg import CODEC_CHOICES, ENCODING_QUALITIES, container_for_codec, hdr_mode_supported, validate_codec_container-from ...core.naming import validate_rename-from ...core.dlss_modes import UPSCALE_ENGINES, dlss_output_size, validate_dlss--VSR_QUALITIES = [("1 - Low", 1), ("2 - Medium", 2), ("3 - High", 3), ("4 - Ultra", 4)]-SCALE_FACTORS = [("1×", 1.0), ("1.5×", 1.5), ("2×", 2.0), ("3×", 3.0), ("4×", 4.0)]-SIZE_MODES = ("Scale factor", "Custom dimensions")-HDR_PRECISIONS = ("Packed 10-bit", "FP16")-HDR_PRECISION_CHOICES = [("Packed 10-bit", "Packed 10-bit"), ("Packed 10-bit (FP16)", "FP16")]-TEXTURE_LIMIT = 16384---@dataclass(slots=True)-class UpscaleOptions:- engine: str = "RTX Video Super Resolution"- dlss_mode: str = "Quality"- dlss_preset: str = "Default"- vsr_enabled: bool = True- vsr_quality: int = 4- size_mode: str = "Scale factor"- scale_factor: float = 2.0- width: int = 3840- height: int = 2160- aspect_lock: bool = True- hdr_enabled: bool = False- hdr_contrast: int = 100- hdr_saturation: int = 100- hdr_middle_gray: int = 50- hdr_peak_luminance: int = 1000- hdr_precision: str = "Packed 10-bit"- codec: str = "H.265 (NVIDIA NVENC)"- container: str = "MKV"- quality: str = "Auto (Default)"- rename_mode: str = "Auto"- custom_suffix: str = "_Upscale"- ai_gpu_uuid: str = "auto"- video_gpu_uuid: str = "auto"- preview_seconds: float | None = None- preview_frames: int | None = None-- def validate(self, *, for_render: bool = True) -> None:- if self.engine not in UPSCALE_ENGINES:- raise ValueError(f"Unknown upscale engine: {self.engine!r}.")- validate_dlss(self.dlss_mode, self.dlss_preset)- for name in ("vsr_enabled", "hdr_enabled", "aspect_lock"):- if not isinstance(getattr(self, name), bool):- raise ValueError(f"{name} must be on or off.")- for name, low, high in (- ("vsr_quality", 0, 4), ("width", 2, TEXTURE_LIMIT), ("height", 2, TEXTURE_LIMIT),- ("hdr_contrast", 0, 200), ("hdr_saturation", 0, 200),- ("hdr_middle_gray", 10, 100), ("hdr_peak_luminance", 400, 2000),- ):- v = getattr(self, name)- if isinstance(v, bool) or not isinstance(v, (int, float)) or not math.isfinite(v) or int(v) != v or not low <= v <= high:- raise ValueError(f"{name.replace('_', ' ')} must be an integer from {low} to {high}.")- if isinstance(self.scale_factor, bool) or not isinstance(self.scale_factor, (int, float)) or not math.isfinite(self.scale_factor) or self.scale_factor < 1:- raise ValueError("Scale factor must be a finite number of at least 1.")- for value, choices, name in ((self.size_mode, SIZE_MODES, "size mode"), (self.hdr_precision, HDR_PRECISIONS, "HDR precision"),- (self.codec, CODEC_CHOICES, "codec"), (self.quality, ENCODING_QUALITIES, "encoding quality")):- if value not in choices:- raise ValueError(f"Unknown {name}: {value!r}.")- if self.container not in ("MP4", "MKV", "MOV"):- raise ValueError("Unknown output container.")- if for_render:- validate_codec_container(self.codec, self.container)- validate_rename(self.rename_mode, self.custom_suffix)- if for_render and self.engine != "DLSS" and not (self.vsr_enabled or self.hdr_enabled):- raise ValueError("Enable RTX Video Super Resolution or RTX Video HDR.")- if self.hdr_enabled and not hdr_mode_supported(self.codec):- raise ValueError("RTX Video HDR requires a 10-bit or higher video codec.")- if self.preview_frames is not None and (isinstance(self.preview_frames, bool) or- not isinstance(self.preview_frames, (int, float)) or- not math.isfinite(self.preview_frames) or- int(self.preview_frames) != self.preview_frames or self.preview_frames < 1):- raise ValueError("Preview frame count must be a positive integer.")- if self.preview_seconds is not None and (isinstance(self.preview_seconds, bool) or- not isinstance(self.preview_seconds, (int, float)) or- not math.isfinite(self.preview_seconds) or self.preview_seconds <= 0):- raise ValueError("Preview duration must be positive and finite.")- if self.preview_seconds is not None and self.preview_frames is not None:- raise ValueError("Select one preview limit.")---SETTING_FIELDS = tuple(f.name for f in fields(UpscaleOptions) if f.name not in {- "ai_gpu_uuid", "video_gpu_uuid", "preview_seconds", "preview_frames",-})---def options_from_settings(settings) -> UpscaleOptions:+from __future__ import annotations++import math+from dataclasses import dataclass, field, fields+from fractions import Fraction++from ...core.ffmpeg import CODEC_CHOICES, ENCODING_QUALITIES, hdr_mode_supported, resolve_container, validate_codec_container+from ...core.naming import validate_rename+from ...core.dlss_modes import UPSCALE_ENGINES, dlss_output_size, validate_dlss++VSR_QUALITIES = [("1 - Low", 1), ("2 - Medium", 2), ("3 - High", 3), ("4 - Ultra", 4)]+SCALE_FACTORS = [("1×", 1.0), ("1.5×", 1.5), ("2×", 2.0), ("3×", 3.0), ("4×", 4.0)]+SIZE_MODES = ("Scale factor", "Custom dimensions")+HDR_PRECISIONS = ("Packed 10-bit", "FP16")+HDR_PRECISION_CHOICES = [("Packed 10-bit", "Packed 10-bit"), ("Packed 10-bit (FP16)", "FP16")]+TEXTURE_LIMIT = 16384+++@dataclass(slots=True)+class UpscaleOptions:+ engine: str = "RTX Video Super Resolution"+ dlss_mode: str = "Quality"+ dlss_preset: str = "Default"+ vsr_enabled: bool = True+ vsr_quality: int = 4+ size_mode: str = "Scale factor"+ scale_factor: float = 2.0+ width: int = 3840+ height: int = 2160+ aspect_lock: bool = True+ hdr_enabled: bool = False+ hdr_contrast: int = 100+ hdr_saturation: int = 100+ hdr_middle_gray: int = 50+ hdr_peak_luminance: int = 1000+ hdr_precision: str = "Packed 10-bit"+ codec: str = "H.265"+ container: str = "MKV"+ quality: str = "Auto (Default)"+ rename_mode: str = "Auto"+ custom_suffix: str = "_Upscale"+ ai_gpu_uuid: str = "auto"+ video_gpu_uuid: str = "auto"+ preview_seconds: float | None = None+ preview_frames: int | None = None++ def validate(self, *, for_render: bool = True) -> None:+ if self.engine not in UPSCALE_ENGINES:+ raise ValueError(f"Unknown upscale engine: {self.engine!r}.")+ validate_dlss(self.dlss_mode, self.dlss_preset)+ for name in ("vsr_enabled", "hdr_enabled", "aspect_lock"):+ if not isinstance(getattr(self, name), bool):+ raise ValueError(f"{name} must be on or off.")+ for name, low, high in (+ ("vsr_quality", 0, 4), ("width", 2, TEXTURE_LIMIT), ("height", 2, TEXTURE_LIMIT),+ ("hdr_contrast", 0, 200), ("hdr_saturation", 0, 200),+ ("hdr_middle_gray", 10, 100), ("hdr_peak_luminance", 400, 2000),+ ):+ v = getattr(self, name)+ if isinstance(v, bool) or not isinstance(v, (int, float)) or not math.isfinite(v) or int(v) != v or not low <= v <= high:+ raise ValueError(f"{name.replace('_', ' ')} must be an integer from {low} to {high}.")+ if isinstance(self.scale_factor, bool) or not isinstance(self.scale_factor, (int, float)) or not math.isfinite(self.scale_factor) or self.scale_factor < 1:+ raise ValueError("Scale factor must be a finite number of at least 1.")+ for value, choices, name in ((self.size_mode, SIZE_MODES, "size mode"), (self.hdr_precision, HDR_PRECISIONS, "HDR precision"),+ (self.codec, CODEC_CHOICES, "codec"), (self.quality, ENCODING_QUALITIES, "encoding quality")):+ if value not in choices:+ raise ValueError(f"Unknown {name}: {value!r}.")+ if self.container not in ("MP4", "MKV", "MOV"):+ raise ValueError("Unknown output container.")+ if for_render:+ validate_codec_container(self.codec, self.container)+ validate_rename(self.rename_mode, self.custom_suffix)+ if for_render and self.engine != "DLSS" and not (self.vsr_enabled or self.hdr_enabled):+ raise ValueError("Enable RTX Video Super Resolution or RTX Video HDR.")+ if self.hdr_enabled and not hdr_mode_supported(self.codec):+ raise ValueError("RTX Video HDR requires a 10-bit or higher video codec.")+ if self.preview_frames is not None and (isinstance(self.preview_frames, bool) or+ not isinstance(self.preview_frames, (int, float)) or+ not math.isfinite(self.preview_frames) or+ int(self.preview_frames) != self.preview_frames or self.preview_frames < 1):+ raise ValueError("Preview frame count must be a positive integer.")+ if self.preview_seconds is not None and (isinstance(self.preview_seconds, bool) or+ not isinstance(self.preview_seconds, (int, float)) or+ not math.isfinite(self.preview_seconds) or self.preview_seconds <= 0):+ raise ValueError("Preview duration must be positive and finite.")+ if self.preview_seconds is not None and self.preview_frames is not None:+ raise ValueError("Select one preview limit.")+++SETTING_FIELDS = tuple(f.name for f in fields(UpscaleOptions) if f.name not in {+ "ai_gpu_uuid", "video_gpu_uuid", "preview_seconds", "preview_frames",+})+++def options_from_settings(settings) -> UpscaleOptions:values = {name: getattr(settings, "upscale_" + name) for name in SETTING_FIELDS}- values["container"] = container_for_codec(values["codec"])- return UpscaleOptions(**values,- ai_gpu_uuid=settings.ai_gpu_uuid, video_gpu_uuid=settings.video_gpu_uuid)---def output_size(width: int, height: int, options: UpscaleOptions, sar: Fraction = Fraction(1)) -> tuple[int, int, str]:- """Return square-pixel output dimensions; width drives a locked custom size."""- options.validate()- display_width = width * float(sar)- if options.engine == "DLSS":- ow, oh = dlss_output_size(math.ceil(display_width), height, options.dlss_mode, even=True)- return ow, oh, ""- if not options.vsr_enabled:- w, h = display_width, float(height)- elif options.size_mode == "Scale factor":- w, h = display_width * options.scale_factor, height * options.scale_factor- else:- w = float(options.width)- h = w * height / display_width if options.aspect_lock else float(options.height)- if not math.isfinite(w) or not math.isfinite(h) or max(w, h) > TEXTURE_LIMIT:- raise ValueError("Requested output exceeds D3D11's 16384-pixel texture dimension. Choose a smaller size.")- # All offered delivery codecs accept even dimensions. Never round below source.- ow, oh = max(2, math.ceil(w / 2) * 2), max(2, math.ceil(h / 2) * 2)- if options.vsr_enabled and (ow < math.ceil(display_width) or oh < height):- raise ValueError("Upscale output must not be smaller than the source. Use 1× for native-resolution enhancement.")- rounding = " (rounded up to even dimensions for encoding)" if (ow != w or oh != h) else ""- return ow, oh, rounding---@dataclass(slots=True)-class UpscaleCapabilities:- gpu: dict- luid: str- vsr: dict- hdr: dict- sdk_version: str = "1.1.0"- worker_version: str = "1.0.0"- bridge_version: str = ""- bridge_status: dict = field(default_factory=dict)---@dataclass(slots=True)-class UpscaleResult:- output_path: str- report_path: str- frames: int- output_width: int- output_height: int- hdr: bool- elapsed_seconds: float- bridge_version: str = ""- memory_path: str = "host_staging"- decode_backend: str = "software"- encode_backend: str = ""- timings: dict = field(default_factory=dict)- bridge_status: dict = field(default_factory=dict)---@dataclass(slots=True)-class UpscaleSuccess:- index: int- input_path: str- result: UpscaleResult---@dataclass(slots=True)-class UpscaleFailure:- index: int- input_path: str- error: str- cancelled: bool = False---@dataclass(slots=True)-class UpscaleBatchResult:- successes: list[UpscaleSuccess]- failures: list[UpscaleFailure]- cancelled: bool- manifest_path: str+ values["container"] = resolve_container(values["codec"], values["container"])+ return UpscaleOptions(**values,+ ai_gpu_uuid=settings.ai_gpu_uuid, video_gpu_uuid=settings.video_gpu_uuid)+++def output_size(width: int, height: int, options: UpscaleOptions, sar: Fraction = Fraction(1)) -> tuple[int, int, str]:+ """Return square-pixel output dimensions; width drives a locked custom size."""+ options.validate()+ display_width = width * float(sar)+ if options.engine == "DLSS":+ ow, oh = dlss_output_size(math.ceil(display_width), height, options.dlss_mode, even=True)+ return ow, oh, ""+ if not options.vsr_enabled:+ w, h = display_width, float(height)+ elif options.size_mode == "Scale factor":+ w, h = display_width * options.scale_factor, height * options.scale_factor+ else:+ w = float(options.width)+ h = w * height / display_width if options.aspect_lock else float(options.height)+ if not math.isfinite(w) or not math.isfinite(h) or max(w, h) > TEXTURE_LIMIT:+ raise ValueError("Requested output exceeds D3D11's 16384-pixel texture dimension. Choose a smaller size.")+ # All offered delivery codecs accept even dimensions. Never round below source.+ ow, oh = max(2, math.ceil(w / 2) * 2), max(2, math.ceil(h / 2) * 2)+ if options.vsr_enabled and (ow < math.ceil(display_width) or oh < height):+ raise ValueError("Upscale output must not be smaller than the source. Use 1× for native-resolution enhancement.")+ rounding = " (rounded up to even dimensions for encoding)" if (ow != w or oh != h) else ""+ return ow, oh, rounding+++@dataclass(slots=True)+class UpscaleCapabilities:+ gpu: dict+ luid: str+ vsr: dict+ hdr: dict+ sdk_version: str = "1.1.0"+ worker_version: str = "1.0.0"+ bridge_version: str = ""+ bridge_status: dict = field(default_factory=dict)+++@dataclass(slots=True)+class UpscaleResult:+ output_path: str+ report_path: str+ frames: int+ output_width: int+ output_height: int+ hdr: bool+ elapsed_seconds: float+ bridge_version: str = ""+ memory_path: str = "host_staging"+ decode_backend: str = "software"+ encode_backend: str = ""+ timings: dict = field(default_factory=dict)+ bridge_status: dict = field(default_factory=dict)+++@dataclass(slots=True)+class UpscaleSuccess:+ index: int+ input_path: str+ result: UpscaleResult+++@dataclass(slots=True)+class UpscaleFailure:+ index: int+ input_path: str+ error: str+ cancelled: bool = False+++@dataclass(slots=True)+class UpscaleBatchResult:+ successes: list[UpscaleSuccess]+ failures: list[UpscaleFailure]+ cancelled: bool+ manifest_path: strdiff --git a/src/upscale/video/preview.py b/src/upscale/video/preview.pyindex 75f1630..28d3e7b 100644--- a/src/upscale/video/preview.py+++ b/src/upscale/video/preview.py@@ -4,37 +4,10 @@ import mathfrom dataclasses import replacefrom pathlib import Path-from ...core.ffmpeg.preview import is_browser_playable, make_browser_preview+from ...core.ffmpeg.preview import LOSSLESS_PREVIEW_CODEC, decode_preview_framefrom .processor import upscale_video-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; 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"- )- try:- 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; 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_upscale_native(path: str,options,@@ -43,7 +16,6 @@ def preview_upscale_native(progress=None,controller=None,output_dir=None,- preview_encoding: str = "Auto",start_seconds: float | None = None,frame_index: int | None = None,preview_seconds: float | None = None,@@ -66,7 +38,7 @@ def preview_upscale_native(# Both preview modes start at the parked timeline frame. Extract only# when seeking: processing the original directly avoids an extra encode# at the beginning of the source.- if start > 0.05:+ if start > 0:from ...core.ffmpeg.preview import extract_preview_subclipif progress:try:@@ -79,12 +51,15 @@ def preview_upscale_native(single_frame=one_frame, controller=controller,)effective_path = temp_clip- opts = replace(- options,- preview_frames=1 if one_frame else None,- preview_seconds=None if one_frame else length_seconds,- )try:+ opts = replace(+ options,+ codec=LOSSLESS_PREVIEW_CODEC,+ container="MKV",+ quality="Auto (Default)",+ preview_frames=1 if one_frame else None,+ preview_seconds=None if one_frame else length_seconds,+ )result = upscale_video(effective_path, opts, progress=progress, controller=controller, output_dir=output_dir)@@ -94,16 +69,11 @@ def preview_upscale_native(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,- )+ display = (decode_preview_frame(result.output_path, controller=controller)+ if one_frame else result.output_path)stamp = (f" f{frame_no} @ {start:.2f}s" if one_frame and start > 0.05 elsef" {length_seconds:g}s @ {start:.2f}s" if not one_frame 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}"+ f"Cached clip: {result.output_path}\nReport: {result.report_path}")diff --git a/src/upscale/video/processor.py b/src/upscale/video/processor.pyindex ffd4ddc..cf620e3 100644--- a/src/upscale/video/processor.py+++ b/src/upscale/video/processor.py@@ -18,7 +18,6 @@ def upscale_video(input_path, options: UpscaleOptions | None = None, progress=Nooutput_dir=None, controller=None, _owns_slot=False,_capabilities=None) -> UpscaleResult:options = replace(options) if options else UpscaleOptions()- options.container = ffmpeg.container_for_codec(options.codec)options.validate()source = Path(input_path).resolve()if not source.is_file():