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
Merserkc12102a12cff
diff --git a/app.py b/app.pyindex 9f9abf0..ce303a9 100644--- a/app.py+++ b/app.py@@ -2,6 +2,7 @@ from __future__ import annotationsimport threadingimport traceback+import sysfrom dataclasses import replacefrom pathlib import Path@@ -14,12 +15,14 @@ from src.images import (ImageConversionOptions,convert_images,decode_image,+ take_image_preview,)from src.runtime import (LOGS,OUTPUTS,cancel_active_job,)+from src.prepare import prepare_runtimefrom src.settings import (CODEC_CHOICES,CONTAINER_CHOICES,@@ -42,6 +45,7 @@ CONFIG_PATH = Path(__file__).resolve().with_name("config.ini")PREVIEW_SECONDS = 3.0AUTOMATIC_MASK_CHOICES = ("Off", "On")_CONFIG_LOCK = threading.Lock()+_CURRENT_SETTINGS: UISettings | None = NoneAPP_CSS = """/* Keep the header links identical even when one URL has been visited. */@@ -149,8 +153,9 @@ def persist_image_settings(image_format: str,image_quality: float,) -> tuple[str, str, float, float, float, float, float, str]:+ global _CURRENT_SETTINGSwith _CONFIG_LOCK:- current = load_settings(CONFIG_PATH)+ current = _CURRENT_SETTINGS or load_settings(CONFIG_PATH)settings = replace(current,nr_preset=nr_preset,@@ -164,7 +169,9 @@ def persist_image_settings(image_format=image_format,image_quality=int(image_quality),)- save_settings(CONFIG_PATH, settings)+ if settings != current:+ save_settings(CONFIG_PATH, settings)+ _CURRENT_SETTINGS = settingsreturn _neural_values(settings)@@ -181,8 +188,9 @@ def persist_video_settings(container: str,quality: str,) -> tuple[str, str, float, float, float, float, float, str]:+ global _CURRENT_SETTINGSwith _CONFIG_LOCK:- current = load_settings(CONFIG_PATH)+ current = _CURRENT_SETTINGS or load_settings(CONFIG_PATH)settings = replace(current,nr_preset=nr_preset,@@ -197,13 +205,17 @@ def persist_video_settings(container=container,quality=quality,)- save_settings(CONFIG_PATH, settings)+ if settings != current:+ save_settings(CONFIG_PATH, settings)+ _CURRENT_SETTINGS = settingsreturn _neural_values(settings)def reset_saved_settings() -> tuple:+ global _CURRENT_SETTINGSwith _CONFIG_LOCK:save_settings(CONFIG_PATH, DEFAULT_SETTINGS)+ _CURRENT_SETTINGS = DEFAULT_SETTINGSneural = _neural_values(DEFAULT_SETTINGS)message = "All Image and Video settings were reset to defaults."return (@@ -413,10 +425,13 @@ def render_image_batch(gallery = []for item in result.successes:- with Image.open(item.output_path) as output:- preview = output.convert("RGBA")- preview.thumbnail((1600, 1200), Image.Resampling.LANCZOS)- gallery.append((preview.copy(), Path(item.output_path).name))+ preview = take_image_preview(item.output_path)+ if preview is None:+ with Image.open(item.output_path) as output:+ preview = output.convert("RGBA")+ preview.thumbnail((1600, 1200), Image.Resampling.LANCZOS)+ preview = preview.copy()+ gallery.append((preview, Path(item.output_path).name))files = [item.output_path for item in result.successes]rows = [[Path(item.input_path).name, "Complete", Path(item.output_path).name, "; ".join(item.warnings)]@@ -481,9 +496,10 @@ def build_neural_controls(settings: UISettings):def build_app() -> gr.Blocks:- """Build the UI and create a default config only when the application is used."""- settings = load_settings(CONFIG_PATH)- save_settings(CONFIG_PATH, settings)+ """Build the UI from the cached settings without rewriting configuration."""+ global _CURRENT_SETTINGS+ settings = _CURRENT_SETTINGS or load_settings(CONFIG_PATH)+ _CURRENT_SETTINGS = settingsupload_types = ["image", ".svg", ".heic", ".heif", *sorted(RAW_EXTENSIONS)]with gr.Blocks(title="DLSS 5 Visual Enhancer") as demo:@@ -715,6 +731,16 @@ def build_app() -> gr.Blocks:def main() -> None:+ print("Preparing DLSS, GPU, image, and FFmpeg runtime before launching the UI...", flush=True)+ try:+ prepared = prepare_runtime()+ except Exception as exc:+ print(f"Startup preparation failed: {exc}", file=sys.stderr, flush=True)+ raise SystemExit(1) from exc+ print(+ f"Runtime ready on {prepared.gpu['display_name']}; launching Gradio.",+ flush=True,+ )OUTPUTS.mkdir(exist_ok=True)LOGS.mkdir(exist_ok=True)demo = build_app()diff --git a/src/ffmpeg.py b/src/ffmpeg.pyindex 44cd27e..e22623a 100644--- a/src/ffmpeg.py+++ b/src/ffmpeg.py@@ -6,6 +6,7 @@ import osimport subprocessimport threadingfrom fractions import Fraction+from functools import lru_cachefrom pathlib import Pathimport av@@ -91,17 +92,31 @@ def _run_json(command: list[str]) -> dict:return json.loads(result.stdout)-def probe_video(path: str | os.PathLike[str]) -> dict:+def probe_video(+ path: str | os.PathLike[str], *, count_mode: str = "exact"+) -> dict:+ """Probe video metadata, optionally counting decoded frames or packets.++ The default remains the legacy exact decoded-frame count for external callers.+ Conversion paths use metadata first and pay for exact counting only as fallback.+ """+ if count_mode not in {"metadata", "exact", "packets"}:+ raise ValueError(f"Unknown video count mode: {count_mode!r}.")+ count_args = {+ "metadata": [],+ "exact": ["-count_frames"],+ "packets": ["-count_packets"],+ }[count_mode]data = _run_json([str(FFPROBE),"-v","error",- "-count_frames",+ *count_args,"-select_streams","v:0","-show_entries",- "stream=index,codec_name,width,height,avg_frame_rate,r_frame_rate,time_base,duration,nb_frames,nb_read_frames,color_primaries,color_transfer,color_space:stream_tags=rotate:stream_side_data=rotation",+ "stream=index,codec_name,width,height,avg_frame_rate,r_frame_rate,time_base,duration,nb_frames,nb_read_frames,nb_read_packets,color_primaries,color_transfer,color_space:stream_tags=rotate:stream_side_data=rotation","-show_entries","format=duration,format_name","-of",@@ -121,8 +136,16 @@ def probe_video(path: str | os.PathLike[str]) -> dict:width, height = int(stream["width"]), int(stream["height"])if rotation in (90, 270):width, height = height, width- frames = int(stream.get("nb_read_frames") or stream.get("nb_frames") or 0)- if frames <= 0:+ if count_mode == "packets":+ frames = int(stream.get("nb_read_packets") or stream.get("nb_frames") or 0)+ frame_count_source = "packets" if stream.get("nb_read_packets") else "metadata"+ elif count_mode == "exact":+ frames = int(stream.get("nb_read_frames") or stream.get("nb_frames") or 0)+ frame_count_source = "decoded" if stream.get("nb_read_frames") else "metadata"+ else:+ frames = int(stream.get("nb_frames") or 0)+ frame_count_source = "metadata" if frames > 0 else "unavailable"+ if count_mode == "exact" and frames <= 0:raise ValueError("Could not determine an exact frame count for this video.")rate_text = stream.get("avg_frame_rate") or stream.get("r_frame_rate") or "30/1"rate = Fraction(rate_text) if rate_text != "0/0" else Fraction(30, 1)@@ -134,6 +157,7 @@ def probe_video(path: str | os.PathLike[str]) -> dict:"coded_height": int(stream["height"]),"rotation": rotation,"frames": frames,+ "frame_count_source": frame_count_source,"fps": float(rate),"rate": rate,"time_base": Fraction(stream.get("time_base") or "1/1000"),@@ -147,6 +171,7 @@ def probe_video(path: str | os.PathLike[str]) -> dict:}+@lru_cache(maxsize=64)def _encoder_probe(codec: str, width: int, height: int) -> bool:command = [str(FFMPEG),@@ -330,7 +355,13 @@ def _probe_rendered_duration(path: Path) -> float:)-def final_mux(temp_video: Path, source: Path, output: Path, container: str) -> None:+def final_mux(+ temp_video: Path,+ source: Path,+ output: Path,+ container: str,+ controller: JobController | None = None,+) -> None:duration = _probe_rendered_duration(temp_video)if container == "MKV":maps = ["-map", "0:v:0", "-map", "1:a?", "-map", "1:s?"]@@ -367,15 +398,23 @@ def final_mux(temp_video: Path, source: Path, output: Path, container: str) -> N*streams,str(output),]- result = subprocess.run(+ process = subprocess.Popen(command,- capture_output=True,+ stdout=subprocess.PIPE,+ stderr=subprocess.PIPE,text=True,encoding="utf-8",errors="replace",)- if result.returncode:- raise RuntimeError("Final audio/metadata mux failed:\n" + result.stderr[-4000:])+ if controller is not None:+ controller.register(process)+ try:+ _stdout, stderr = process.communicate()+ finally:+ if controller is not None:+ controller.unregister(process)+ if process.returncode:+ raise RuntimeError("Final audio/metadata mux failed:\n" + stderr[-4000:])def preview_frame_count(source: Path, seconds: float) -> int:diff --git a/src/images.py b/src/images.pyindex 935cb53..f31f54d 100644--- a/src/images.py+++ b/src/images.py@@ -1,12 +1,15 @@from __future__ import annotations-import hashlibimport ioimport jsonimport os+import threadingimport timeimport zipfile+from collections import OrderedDict+from concurrent.futures import Future, ThreadPoolExecutorfrom dataclasses import asdict, dataclass, field+from functools import lru_cachefrom pathlib import Pathfrom typing import Callable, Iterable@@ -20,16 +23,11 @@ from PIL import Image, ImageCms, ImageOpsfrom .runtime import (LOGS,OUTPUTS,- RUNTIME,- WORKER,Cancelled,DLSSFrameSession,active_job,- detect_gpu,- inspect_runtime_bundle,resize_fit,validate_gpu_runtime,- validate_runtime_files,verify_feature_18,write_failure_report,)@@ -46,6 +44,9 @@ Image.MAX_IMAGE_PIXELS = 100_000_000IMAGE_FORMATS = ("PNG", "JPEG", "WebP", "AVIF", "TIFF")IMAGE_EXTENSIONS = {"PNG": ".png", "JPEG": ".jpg", "WebP": ".webp", "AVIF": ".avif", "TIFF": ".tiff"}+_PREVIEW_CACHE_LIMIT = 32+_preview_cache: OrderedDict[str, Image.Image] = OrderedDict()+_preview_cache_lock = threading.Lock()RAW_EXTENSIONS = {".3fr", ".arw", ".bay", ".cap", ".cr2", ".cr3", ".dcr", ".dcs", ".dng",".drf", ".eip", ".erf", ".fff", ".gpr", ".iiq", ".k25", ".kdc", ".mdc",@@ -66,7 +67,7 @@ class ImageConversionOptions:output_format: str = "PNG"quality: int = 95preserve_metadata: bool = True- warmup_frames: int = 120+ warmup_frames: int = 0nr_preset: str = "Default"automatic_mask: bool = False@@ -126,6 +127,7 @@ class _ImageProbe:height: intoutput_width: intoutput_height: int+ decoded: _DecodedImage | None = None@dataclass(slots=True)@@ -137,6 +139,18 @@ class _DecodedImage:warnings: list[str]+@dataclass(slots=True)+class _ImageReportData:+ decoder: str+ metadata: dict[str, object]+ warnings: list[str]+++def _report_data(decoded: _DecodedImage) -> _ImageReportData:+ """Keep diagnostics without retaining the decoded pixel and alpha arrays."""+ return _ImageReportData(decoded.decoder, decoded.metadata, decoded.warnings)++def _validate_options(options: ImageConversionOptions) -> ConversionOptions:if options.output_format not in IMAGE_FORMATS:raise ValueError(f"Unknown image output format: {options.output_format!r}.")@@ -195,10 +209,63 @@ def probe_image(path: str | os.PathLike[str]) -> tuple[int, int]:return width, height+@lru_cache(maxsize=1)def _srgb_profile_bytes() -> bytes:return ImageCms.ImageCmsProfile(ImageCms.createProfile("sRGB")).tobytes()+def initialize_image_runtime() -> None:+ """Initialize reusable image color-management state during app preparation."""+ _srgb_profile_bytes()+++def take_image_preview(output_path: str | os.PathLike[str]) -> Image.Image | None:+ """Return and remove a UI thumbnail created from the rendered frame in memory."""+ key = str(Path(output_path).resolve())+ with _preview_cache_lock:+ return _preview_cache.pop(key, None)+++def _remember_image_preview(+ output_path: Path, rgba: np.ndarray, output_format: str+) -> None:+ image = Image.fromarray(rgba, mode="RGBA")+ try:+ if output_format == "JPEG":+ background = Image.new("RGBA", image.size, (255, 255, 255, 255))+ background.alpha_composite(image)+ preview = background+ else:+ preview = image.copy()+ preview.thumbnail((1600, 1200), Image.Resampling.LANCZOS)+ key = str(output_path.resolve())+ with _preview_cache_lock:+ previous = _preview_cache.pop(key, None)+ if previous is not None:+ previous.close()+ _preview_cache[key] = preview+ while len(_preview_cache) > _PREVIEW_CACHE_LIMIT:+ _unused_key, unused = _preview_cache.popitem(last=False)+ unused.close()+ finally:+ image.close()+++def _encode_image(+ output: Path,+ rgba: np.ndarray,+ options: ImageConversionOptions,+ metadata: dict[str, object],+) -> list[str]:+ warnings = save_image(output, rgba, options, metadata)+ try:+ _remember_image_preview(output, rgba, options.output_format)+ except Exception:+ # A UI convenience must never invalidate an otherwise correct output.+ pass+ return warnings++def decode_image(path: str | os.PathLike[str]) -> _DecodedImage:source = Path(path).resolve()image, decoder = _open_pillow_source(source)@@ -216,9 +283,15 @@ def decode_image(path: str | os.PathLike[str]) -> _DecodedImage:if original_mode not in {"1", "L", "LA", "P", "RGB", "RGBA", "CMYK"}:warnings.append(f"Converted {original_mode} source data to 8-bit SDR sRGB.")- rgba_image = image.convert("RGBA")- alpha_image = rgba_image.getchannel("A")- rgb_image = rgba_image.convert("RGB")+ has_alpha = image.mode in {"LA", "RGBA"} or (+ image.mode == "P" and "transparency" in info+ )+ alpha_image = (+ image.convert("RGBA").getchannel("A")+ if has_alpha+ else Image.new("L", image.size, 255)+ )+ rgb_image = image.convert("RGB")icc_profile = info.get("icc_profile")if isinstance(icc_profile, bytes) and icc_profile:try:@@ -234,7 +307,9 @@ def decode_image(path: str | os.PathLike[str]) -> _DecodedImage:rgb = np.asarray(rgb_image, dtype=np.uint8)alpha = np.asarray(alpha_image, dtype=np.uint8)- rgba = np.dstack((rgb, alpha))+ rgba = np.empty((*rgb.shape[:2], 4), dtype=np.uint8)+ rgba[..., :3] = rgb+ rgba[..., 3] = alphaexif = image.getexif()if exif:exif[274] = 1@@ -284,14 +359,19 @@ def save_image(warnings: list[str] = []args = _metadata_save_args(metadata, output_format) if options.preserve_metadata else {}if output_format == "PNG":- args.update(optimize=True, compress_level=9)+ args.update(optimize=False, compress_level=6)elif output_format == "TIFF":args.update(compression="tiff_deflate")elif output_format == "JPEG":background = Image.new("RGBA", image.size, (255, 255, 255, 255))background.alpha_composite(image)image = background.convert("RGB")- args.update(quality=int(options.quality), subsampling=0, optimize=True, progressive=True)+ args.update(+ quality=int(options.quality),+ subsampling=0,+ optimize=False,+ progressive=False,+ )if np.any(rgba[..., 3] != 255):warnings.append("Transparency was composited over white for JPEG output.")elif output_format == "WebP":@@ -319,7 +399,7 @@ def _output_path(source: Path, output_format: str, stamp: str, index: int) -> Padef _write_report(result: ImageConversionResult,options: ImageConversionOptions,- decoded: _DecodedImage,+ decoded: _ImageReportData,gpu: dict,session: DLSSFrameSession,evidence: dict[str, object],@@ -352,9 +432,10 @@ def _write_report("ngx_setup_result": f"0x{session.setup_result:08X}","carrier_create_result": evidence["carrier_create_result"],"native_settings": session.native_settings,- "model_sha256": hashlib.sha256((RUNTIME / "nvngx_dlssnr.dll").read_bytes()).hexdigest(),- "worker_sha256": hashlib.sha256(WORKER.read_bytes()).hexdigest(),+ "model_sha256": session.runtime_bundle["neural_runtime"]["sha256"].lower(),+ "worker_sha256": session.runtime_bundle["worker"]["sha256"].lower(),"worker_log": session.worker_logs,+ "worker_log_dropped_lines": session.worker_log_dropped_lines,"dlssnr_evidence": evidence["evidence"],"elapsed_seconds": result.elapsed_seconds,}@@ -383,7 +464,7 @@ def _build_manifest_and_zip(zip_path = OUTPUTS / f"DLSS5_IMAGE_BATCH_{stamp}.zip"temporary = zip_path.with_name(f".{zip_path.stem}.{time.time_ns()}.zip")try:- with zipfile.ZipFile(temporary, "w", compression=zipfile.ZIP_DEFLATED, compresslevel=6) as archive:+ with zipfile.ZipFile(temporary, "w", compression=zipfile.ZIP_STORED) as archive:for item in successes:archive.write(item.output_path, arcname=Path(item.output_path).name)os.replace(temporary, zip_path)@@ -398,12 +479,14 @@ def convert_images(options: ImageConversionOptions | None = None,progress: Callable[[float, str], None] | None = None,) -> ImageBatchResult:+ from .prepare import prepare_runtime+options = options or ImageConversionOptions()neural = _validate_options(options)paths = [Path(path).resolve() for path in input_paths]if not paths:raise ValueError("Choose at least one image.")- validate_runtime_files()+ prepared_runtime = prepare_runtime()OUTPUTS.mkdir(exist_ok=True)LOGS.mkdir(exist_ok=True)stamp = time.strftime("%Y%m%d-%H%M%S") + f"-{time.time_ns() % 1_000_000:06d}"@@ -411,11 +494,25 @@ def convert_images(probes: list[_ImageProbe] = []for index, path in enumerate(paths):try:- width, height = probe_image(path)+ decoded: _DecodedImage | None = None+ if path.suffix.lower() in {*RAW_EXTENSIONS, ".svg"}:+ decoded = decode_image(path)+ height, width = decoded.rgba.shape[:2]+ if width < 64 or height < 64:+ raise ValueError(+ f"{path.name} is {width}×{height}; DLSS requires both input "+ "dimensions to be at least 64 pixels."+ )+ else:+ width, height = probe_image(path)output_width, output_height = resolve_output_size(width, height, options.upscaling_factor)- probes.append(_ImageProbe(index, path, width, height, output_width, output_height))+ probes.append(+ _ImageProbe(+ index, path, width, height, output_width, output_height, decoded+ )+ )except Exception as exc:failures_by_index[index] = ImageConversionFailure(str(path), str(exc))@@ -433,9 +530,11 @@ def convert_images(cancelled = Falsegpu: dict | None = Noneprocessed_total = 0+ decode_executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix="dlss5-image-decode")+ encode_executor = ThreadPoolExecutor(max_workers=2, thread_name_prefix="dlss5-image-encode")with active_job() as controller:- gpu = detect_gpu()- runtime_bundle = inspect_runtime_bundle()+ gpu = dict(prepared_runtime.gpu)+ runtime_bundle = prepared_runtime.runtime_bundletry:validate_gpu_runtime(gpu, runtime_bundle)except Exception as exc:@@ -450,118 +549,201 @@ def convert_images(if progress:progress(0.0, f"Starting feature 18 on {gpu['display_name']}")total = len(probes)- for (output_width, output_height), group in groups.items():- cursor = 0- while cursor < len(group):- if controller.cancel.is_set():- cancelled = True- break- remaining = group[cursor:]- first = remaining[0]- try:- factor, mode = resolve_upscaling_mode(neural.upscaling_factor)- session = DLSSFrameSession(- input_width=first.width,- input_height=first.height,- output_width=output_width,- output_height=output_height,- frame_count=len(remaining),- warmup_frames=neural.warmup_frames,- factor=factor,- mode=mode,- native_settings=resolve_native_settings(neural),- gpu=gpu,- runtime_bundle=runtime_bundle,- controller=controller,- )- except Exception as exc:- controller.terminate_processes()- report_path = write_failure_report(- operation="image-batch-dlss-setup",- source="; ".join(str(item.path) for item in remaining),- error=exc,- gpu=gpu,- runtime_bundle=runtime_bundle,- )- failure = f"{exc}\nDiagnostic report: {report_path}"- for item in remaining:- failures_by_index[item.index] = ImageConversionFailure(str(item.path), failure)- break-- segment: list[tuple[_ImageProbe, ImageConversionResult, _DecodedImage]] = []- sent = 0- interrupted = False- close_error: Exception | None = None+ factor, mode = resolve_upscaling_mode(neural.upscaling_factor)+ native_settings = resolve_native_settings(neural)+ try:+ for (output_width, output_height), group in groups.items():+ cursor = 0while cursor < len(group):- item = group[cursor]- started = time.perf_counter()if controller.cancel.is_set():cancelled = True- interrupted = True- session.abort()break- if progress:- progress(processed_total / max(1, total), f"Preparing {item.path.name}")+ remaining = group[cursor:]+ first = remaining[0]try:- decoded = decode_image(item.path)+ session = DLSSFrameSession(+ input_width=first.width,+ input_height=first.height,+ output_width=output_width,+ output_height=output_height,+ frame_count=len(remaining),+ warmup_frames=neural.warmup_frames,+ factor=factor,+ mode=mode,+ native_settings=native_settings,+ gpu=gpu,+ runtime_bundle=runtime_bundle,+ controller=controller,+ )except Exception as exc:- failures_by_index[item.index] = ImageConversionFailure(str(item.path), str(exc))+ controller.terminate_processes()+ report_path = write_failure_report(+ operation="image-batch-dlss-setup",+ source="; ".join(str(item.path) for item in remaining),+ error=exc,+ gpu=gpu,+ runtime_bundle=runtime_bundle,+ )+ failure = f"{exc}\nDiagnostic report: {report_path}"+ for item in remaining:+ failures_by_index[item.index] = ImageConversionFailure(str(item.path), failure)+ break++ segment: list[+ tuple[+ _ImageProbe,+ ImageConversionResult,+ _ImageReportData,+ Future[list[str]],+ float,+ ]+ ] = []+ sent = 0+ motion = np.zeros(+ (session.render_height, session.render_width, 2), dtype=np.float16+ )+ interrupted = False+ close_error: Exception | None = None+ decode_future: Future[_DecodedImage] | None = decode_executor.submit(+ lambda probe=group[cursor]: probe.decoded or decode_image(probe.path)+ )+ while cursor < len(group):+ item = group[cursor]+ started = time.perf_counter()+ if controller.cancel.is_set():+ cancelled = True+ interrupted = True+ session.abort()+ break+ if progress:+ progress(processed_total / max(1, total), f"Preparing {item.path.name}")+ try:+ assert decode_future is not None+ decoded = decode_future.result()+ item.decoded = None+ next_cursor = cursor + 1+ decode_future = (+ decode_executor.submit(+ lambda probe=group[next_cursor]:+ probe.decoded or decode_image(probe.path)+ )+ if next_cursor < len(group)+ else None+ )+ except Exception as exc:+ failures_by_index[item.index] = ImageConversionFailure(str(item.path), str(exc))+ cursor += 1+ processed_total += 1+ session.abort()+ interrupted = True+ break+ try:+ render_rgba = resize_fit(+ decoded.rgba, session.render_width, session.render_height+ )+ processed, _pts = session.process(+ index=sent,+ rgba=render_rgba,+ motion=motion,+ reset=True,+ pts=sent,+ )+ alpha = (+ decoded.alpha+ if decoded.alpha.shape == (output_height, output_width)+ else cv2.resize(+ decoded.alpha,+ (output_width, output_height),+ interpolation=cv2.INTER_LANCZOS4,+ )+ )+ processed[..., 3] = alpha+ output = _output_path(item.path, options.output_format, stamp, item.index)+ result = ImageConversionResult(+ str(item.path),+ str(output),+ "",+ time.perf_counter() - started,+ str(gpu["display_name"]),+ item.width,+ item.height,+ session.render_width,+ session.render_height,+ output_width,+ output_height,+ float(options.upscaling_factor),+ str(session.mode["name"]),+ options.output_format,+ list(decoded.warnings),+ )+ encoding = encode_executor.submit(+ _encode_image, output, processed, options, decoded.metadata+ )+ segment.append(+ (item, result, _report_data(decoded), encoding, started)+ )+ # Keep at most two full rendered frames queued for encoding.+ # Completed futures retain only their small warning list.+ if len(segment) > 2:+ segment[-3][3].result()+ sent += 1+ except Cancelled:+ cancelled = True+ session.abort()+ interrupted = True+ break+ except Exception as exc:+ session.abort()+ report_path = write_failure_report(+ operation="image-render",+ source=str(item.path),+ error=exc,+ gpu=gpu,+ runtime_bundle=runtime_bundle,+ worker_code=session.worker.poll(),+ worker_logs=session.worker_logs,+ reshade_lines=session.reshade_diagnostics(),+ )+ failures_by_index[item.index] = ImageConversionFailure(+ str(item.path), f"{exc}\nDiagnostic report: {report_path}"+ )+ interrupted = True+ cursor += 1+ processed_total += 1+ breakcursor += 1processed_total += 1- session.abort()- interrupted = True- break+ if progress:+ progress(processed_total / total, f"Rendered {item.path.name}")++ if not segment and interrupted:+ if cancelled:+ break+ continue+ if not interrupted:+ try:+ session.close()+ except Exception as exc:+ close_error = exctry:- render_rgba = resize_fit(- decoded.rgba, session.render_width, session.render_height- )- motion = np.zeros(- (session.render_height, session.render_width, 2), dtype=np.float16- )- processed, _pts = session.process(- index=sent,- rgba=render_rgba,- motion=motion,- reset=True,- pts=sent,- )- alpha = cv2.resize(- decoded.alpha,- (output_width, output_height),- interpolation=cv2.INTER_LANCZOS4,- )- processed[..., 3] = alpha- output = _output_path(item.path, options.output_format, stamp, item.index)- encoding_warnings = save_image(output, processed, options, decoded.metadata)- result = ImageConversionResult(- str(item.path),- str(output),- "",- time.perf_counter() - started,- str(gpu["display_name"]),- item.width,- item.height,- session.render_width,- session.render_height,- output_width,- output_height,- float(options.upscaling_factor),- str(session.mode["name"]),- options.output_format,- [*decoded.warnings, *encoding_warnings],+ if close_error:+ raise close_error+ evidence = verify_feature_18(+ session.worker_logs, session.reshade_log_text())- segment.append((item, result, decoded))- sent += 1- except Cancelled:- cancelled = True- session.abort()- interrupted = True- break+ assert gpu is not None+ for item, result, decoded, encoding, item_started in segment:+ result.warnings.extend(encoding.result())+ result.elapsed_seconds = time.perf_counter() - item_started+ for item, result, decoded, _encoding, _item_started in segment:+ result.report_path = _write_report(+ result, options, decoded, gpu, session, evidence+ )+ successes_by_index[item.index] = resultexcept Exception as exc:- session.abort()report_path = write_failure_report(- operation="image-render",- source=str(item.path),+ operation="image-batch-verification",+ source="; ".join(str(item.path) for item, *_rest in segment),error=exc,gpu=gpu,runtime_bundle=runtime_bundle,@@ -569,60 +751,21 @@ def convert_images(worker_logs=session.worker_logs,reshade_lines=session.reshade_diagnostics(),)- failures_by_index[item.index] = ImageConversionFailure(- str(item.path), f"{exc}\nDiagnostic report: {report_path}"- )- interrupted = True- cursor += 1- processed_total += 1- break- cursor += 1- processed_total += 1- if progress:- progress(processed_total / total, f"Rendered {item.path.name}")-- if not segment and interrupted:+ failure = f"{exc}\nDiagnostic report: {report_path}"+ for item, result, _decoded, encoding, _item_started in segment:+ if not encoding.done():+ encoding.cancel()+ output = Path(result.output_path)+ if output.exists():+ output.unlink()+ failures_by_index[item.index] = ImageConversionFailure(str(item.path), failure)if cancelled:break- continue- if not interrupted:- try:- session.close()- except Exception as exc:- close_error = exc- try:- if close_error:- raise close_error- evidence = verify_feature_18(- session.worker_logs, session.reshade_log_text()- )- assert gpu is not None- for item, result, decoded in segment:- result.report_path = _write_report(- result, options, decoded, gpu, session, evidence- )- successes_by_index[item.index] = result- except Exception as exc:- report_path = write_failure_report(- operation="image-batch-verification",- source="; ".join(str(item.path) for item, _result, _decoded in segment),- error=exc,- gpu=gpu,- runtime_bundle=runtime_bundle,- worker_code=session.worker.poll(),- worker_logs=session.worker_logs,- reshade_lines=session.reshade_diagnostics(),- )- failure = f"{exc}\nDiagnostic report: {report_path}"- for item, result, _decoded in segment:- output = Path(result.output_path)- if output.exists():- output.unlink()- failures_by_index[item.index] = ImageConversionFailure(str(item.path), failure)if cancelled:break- if cancelled:- break+ finally:+ decode_executor.shutdown(wait=True, cancel_futures=True)+ encode_executor.shutdown(wait=True, cancel_futures=True)if cancelled:completed = set(successes_by_index) | set(failures_by_index)for probe in probes:diff --git a/src/prepare.py b/src/prepare.pynew file mode 100644index 0000000..eb74d0d--- /dev/null+++ b/src/prepare.py@@ -0,0 +1,141 @@+from __future__ import annotations++import atexit+import mmap+import subprocess+import threading+from dataclasses import dataclass, field+from pathlib import Path+from typing import Any++from .runtime import (+ ADDON,+ FFMPEG,+ FFPROBE,+ NEURAL_RUNTIME,+ RUNTIME,+ WORKER,+ detect_gpu,+ inspect_runtime_bundle,+ validate_gpu_runtime,+ validate_runtime_files,+)+++@dataclass(slots=True)+class PreparedRuntime:+ """Reusable, source-independent state prepared once for this process."""++ gpu: dict[str, Any]+ runtime_bundle: dict[str, Any]+ encoder_inventory: dict[str, bool]+ warmed_files: tuple[str, ...]+ _mappings: list[mmap.mmap] = field(default_factory=list, repr=False)++ def close(self) -> None:+ while self._mappings:+ mapping = self._mappings.pop()+ try:+ mapping.close()+ except (BufferError, OSError):+ pass+++_PREPARE_LOCK = threading.Lock()+_PREPARED: PreparedRuntime | None = None+++def _warm_mapping(path: Path) -> mmap.mmap | None:+ if not path.is_file() or path.stat().st_size == 0:+ return None+ with path.open("rb") as stream:+ mapping = mmap.mmap(stream.fileno(), 0, access=mmap.ACCESS_READ)+ # Touch regularly spaced pages. Sequential hashing already warms the largest+ # model; this also covers un-hashed loader and FFmpeg components.+ checksum = 0+ for offset in range(0, len(mapping), 64 * 1024):+ checksum ^= mapping[offset]+ checksum ^= mapping[-1]+ del checksum+ return mapping+++def _encoder_inventory() -> dict[str, bool]:+ result = subprocess.run(+ [str(FFMPEG), "-hide_banner", "-encoders"],+ capture_output=True,+ text=True,+ encoding="utf-8",+ errors="replace",+ )+ if result.returncode:+ raise RuntimeError(result.stderr.strip() or "FFmpeg encoder inventory failed.")+ output = result.stdout+ return {+ "h264_nvenc": "h264_nvenc" in output,+ "hevc_nvenc": "hevc_nvenc" in output,+ "av1_nvenc": "av1_nvenc" in output,+ "prores_ks": "prores_ks" in output,+ }+++def prepare_runtime() -> PreparedRuntime:+ """Prepare all reusable runtime state before UI launch or first conversion."""+ global _PREPARED+ if _PREPARED is not None:+ return _PREPARED+ with _PREPARE_LOCK:+ if _PREPARED is not None:+ return _PREPARED++ validate_runtime_files()+ gpu = detect_gpu()+ runtime_bundle = inspect_runtime_bundle()+ validate_gpu_runtime(gpu, runtime_bundle)+ inventory = _encoder_inventory()++ # Initialize Pillow's reusable sRGB profile and optional image backends.+ from .images import initialize_image_runtime++ initialize_image_runtime()++ paths = (+ WORKER,+ RUNTIME / "dxgi.dll",+ ADDON,+ RUNTIME / "nvngx_dlss.dll",+ NEURAL_RUNTIME,+ FFMPEG,+ FFPROBE,+ )+ mappings: list[mmap.mmap] = []+ try:+ for path in paths:+ mapping = _warm_mapping(path)+ if mapping is not None:+ mappings.append(mapping)+ except Exception:+ for mapping in mappings:+ mapping.close()+ raise++ _PREPARED = PreparedRuntime(+ gpu=dict(gpu),+ runtime_bundle=runtime_bundle,+ encoder_inventory=inventory,+ warmed_files=tuple(str(path.resolve()) for path in paths),+ _mappings=mappings,+ )+ return _PREPARED+++def close_prepared_runtime() -> None:+ global _PREPARED+ with _PREPARE_LOCK:+ prepared = _PREPARED+ _PREPARED = None+ if prepared is not None:+ prepared.close()+++atexit.register(close_prepared_runtime)diff --git a/src/runtime.py b/src/runtime.pyindex 6975dbe..1123b39 100644--- a/src/runtime.py+++ b/src/runtime.py@@ -7,7 +7,9 @@ import structimport subprocessimport threadingimport time+from collections import dequefrom contextlib import contextmanager+from functools import lru_cachefrom pathlib import Pathfrom typing import Any, Iterator@@ -76,6 +78,7 @@ def inspect_runtime_bundle(neural = neural_path or NEURAL_RUNTIMEaddon_hash = _file_sha256(addon)neural_hash = _file_sha256(neural)+ worker_hash = _file_sha256(WORKER)known_pair = (addon_hash == EXPECTED_AMPERE_ADDON_SHA256and neural_hash == EXPECTED_AMPERE_NEURAL_SHA256@@ -98,6 +101,10 @@ def inspect_runtime_bundle("version": "310.8.SF-v2","release": "DLSS NR 310.8.SF-v2",},+ "worker": {+ "path": str(WORKER.resolve()),+ "sha256": worker_hash,+ },}@@ -221,6 +228,12 @@ class JobController:def register(self, process: subprocess.Popen) -> None:with self._lock:self._processes.append(process)+ cancelled = self.cancel.is_set()+ if cancelled and process.poll() is None:+ try:+ process.terminate()+ except OSError:+ passdef unregister(self, process: subprocess.Popen) -> None:with self._lock:@@ -280,8 +293,61 @@ def drain_text(stream, lines: list[str]) -> None:lines.append(raw.decode("utf-8", "replace").rstrip())+class BoundedLogBuffer:+ """Keep diagnostic evidence and a bounded tail instead of every frame log."""++ _IMPORTANT = (+ "profile applied",+ "DLSS 5 add-on",+ "carrier ready",+ "stream source",+ "optimal settings",+ "complete:",+ "failed",+ "error",+ "exception",+ )++ def __init__(self, max_tail: int = 500, max_important: int = 100) -> None:+ self._tail: deque[str] = deque(maxlen=max_tail)+ self._important: list[str] = []+ self._max_important = max_important+ self._seen = 0+ self._lock = threading.Lock()++ def append(self, line: str) -> None:+ with self._lock:+ self._seen += 1+ self._tail.append(line)+ lowered = line.casefold()+ if (+ len(self._important) < self._max_important+ and any(marker.casefold() in lowered for marker in self._IMPORTANT)+ ):+ self._important.append(line)++ def snapshot(self) -> list[str]:+ with self._lock:+ important = list(self._important)+ tail = list(self._tail)+ seen: set[str] = set()+ return [line for line in [*important, *tail] if not (line in seen or seen.add(line))]++ @property+ def dropped_lines(self) -> int:+ with self._lock:+ return max(0, self._seen - len(self._tail))+++def drain_bounded_text(stream, buffer: BoundedLogBuffer) -> None:+ for raw in iter(stream.readline, b""):+ buffer.append(raw.decode("utf-8", "replace").rstrip())++def resize_fit(rgba: np.ndarray, width: int, height: int) -> np.ndarray:source_height, source_width = rgba.shape[:2]+ if source_width == width and source_height == height:+ return np.ascontiguousarray(rgba, dtype=np.uint8)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))))@@ -304,6 +370,7 @@ def rotate_frame(frame: np.ndarray, rotation: int) -> np.ndarray:return frame+@lru_cache(maxsize=1)def detect_gpu() -> dict:command = ["nvidia-smi",@@ -368,6 +435,23 @@ def _read_exact(stream, size: int) -> bytes:return bytes(chunks)+def _read_exact_into(stream, target: np.ndarray) -> None:+ view = memoryview(target).cast("B")+ offset = 0+ while offset < len(view):+ count = stream.readinto(view[offset:])+ if not count:+ raise EOFError(+ f"Native worker stopped after {offset} of {len(view)} output bytes"+ )+ offset += count+++def _array_bytes(array: np.ndarray, dtype: np.dtype) -> memoryview:+ contiguous = np.ascontiguousarray(array, dtype=dtype)+ return memoryview(contiguous).cast("B")++class DLSSFrameSession:"""A reusable native DLSSNR feature-18 frame stream."""@@ -388,7 +472,7 @@ class DLSSFrameSession:controller: JobController,) -> None:self.controller = controller- self.worker_logs: list[str] = []+ self._worker_log_buffer = BoundedLogBuffer()self.closed = Falseself.factor = factorself.mode = mode@@ -396,9 +480,14 @@ class DLSSFrameSession:self.gpu = gpuself.runtime_bundle = runtime_bundlereshade_log_path = RUNTIME / "ReShade.log"- self._reshade_log_baseline = (- reshade_log_path.read_bytes() if reshade_log_path.exists() else b""- )+ self._reshade_log_baseline_size = 0+ self._reshade_log_baseline_tail = b""+ if reshade_log_path.exists():+ self._reshade_log_baseline_size = reshade_log_path.stat().st_size+ with reshade_log_path.open("rb") as stream:+ tail_size = min(256, self._reshade_log_baseline_size)+ stream.seek(self._reshade_log_baseline_size - tail_size)+ self._reshade_log_baseline_tail = stream.read(tail_size)creation_flags = getattr(subprocess, "CREATE_NO_WINDOW", 0)self.worker = subprocess.Popen([str(WORKER), "--video"],@@ -411,8 +500,8 @@ class DLSSFrameSession:controller.register(self.worker)assert self.worker.stderr is not Noneself.worker_thread = threading.Thread(- target=drain_text,- args=(self.worker.stderr, self.worker_logs),+ target=drain_bounded_text,+ args=(self.worker.stderr, self._worker_log_buffer),daemon=True,)self.worker_thread.start()@@ -506,27 +595,41 @@ class DLSSFrameSession:path = RUNTIME / "ReShade.log"if not path.exists():return ""- current = path.read_bytes()- if self._reshade_log_baseline and current.startswith(self._reshade_log_baseline):- current = current[len(self._reshade_log_baseline) :]- return current.decode("utf-8", errors="replace")+ with path.open("rb") as stream:+ size = path.stat().st_size+ can_seek = size >= self._reshade_log_baseline_size+ tail = self._reshade_log_baseline_tail+ if can_seek and tail:+ stream.seek(self._reshade_log_baseline_size - len(tail))+ can_seek = stream.read(len(tail)) == tail+ stream.seek(self._reshade_log_baseline_size if can_seek else 0)+ current = stream.read()+ text = current.decode("utf-8", errors="replace")+ process_marker = f"[{self.worker.pid}]"+ process_lines = [line for line in text.splitlines() if process_marker in line]+ return "\n".join(process_lines) if process_lines else text++ @property+ def worker_logs(self) -> list[str]:+ return self._worker_log_buffer.snapshot()++ @property+ def worker_log_dropped_lines(self) -> int:+ return self._worker_log_buffer.dropped_linesdef reshade_diagnostics(self, limit: int = 300) -> list[str]:"""Return new log lines from this worker, favoring feature-18 evidence."""lines = self.reshade_log_text().splitlines()- process_marker = f"[{self.worker.pid}]"- current_process = [line for line in lines if process_marker in line]- selected = current_process or linesrelevant = [line- for line in selected+ for line in linesif "DLSS 5 Neural Rendering" in lineor "DLSSNR" in lineor "feature 18" in lineor "exception" in line.lower()or "failed" in line.lower()]- return (relevant or selected)[-limit:]+ return (relevant or lines)[-limit:]def process(self,@@ -542,8 +645,8 @@ class DLSSFrameSession:assert self.worker.stdin is not None and self.worker.stdout is not Noneframe_header = struct.pack("<4Iq", FRAME_MAGIC, index, int(reset), 0, pts)self.worker.stdin.write(frame_header)- self.worker.stdin.write(np.ascontiguousarray(rgba, dtype=np.uint8).tobytes())- self.worker.stdin.write(np.ascontiguousarray(motion, dtype=np.float16).tobytes())+ self.worker.stdin.write(_array_bytes(rgba, np.dtype(np.uint8)))+ self.worker.stdin.write(_array_bytes(motion, np.dtype(np.float16)))self.worker.stdin.flush()try:result_header = _read_exact(self.worker.stdout, struct.calcsize("<5Iq"))@@ -569,10 +672,9 @@ class DLSSFrameSession:raise RuntimeError(f"Direct feature-18 evaluation failed on frame {index}: 0x{ngx_result:08X}")- output = np.frombuffer(- _read_exact(self.worker.stdout, byte_count), dtype=np.uint8- ).reshape(self.output_height, self.output_width, 4)- return output.copy(), out_pts+ output = np.empty((self.output_height, self.output_width, 4), dtype=np.uint8)+ _read_exact_into(self.worker.stdout, output)+ return output, out_ptsdef close(self) -> None:if self.closed:diff --git a/src/video.py b/src/video.pyindex 9b39a88..19ff875 100644--- a/src/video.py+++ b/src/video.py@@ -1,10 +1,11 @@from __future__ import annotations-import hashlibimport jsonimport mathimport os+import queueimport shutil+import threadingimport timefrom contextlib import suppressfrom dataclasses import asdict, dataclass@@ -21,17 +22,11 @@ from .runtime import (JOBS,LOGS,OUTPUTS,- RUNTIME,- WORKER,Cancelled,DLSSFrameSession,active_job,- detect_gpu,- inspect_runtime_bundle,resize_fit,rotate_frame,- validate_gpu_runtime,- validate_runtime_files,verify_feature_18,write_failure_report,)@@ -56,7 +51,7 @@ class ConversionOptions:container: str = "MP4"quality: str = "Auto (Default)"preserve_hdr: bool = False- warmup_frames: int = 120+ warmup_frames: int = 0preview_seconds: float | None = Nonepreview_frames: int | None = Nonenr_preset: str = "Default"@@ -234,6 +229,7 @@ class TemporalGuideGenerator:self.flow_width = max(64, int(round(width * scale / 2) * 2))self.flow_height = max(64, int(round(height * scale / 2) * 2))self.previous_gray: np.ndarray | None = None+ self.zero_motion = np.zeros((height, width, 2), dtype=np.float16)self.dis = cv2.DISOpticalFlow_create(cv2.DISOPTICAL_FLOW_PRESET_MEDIUM)self.dis.setUseSpatialPropagation(True)self.dis.setFinestScale(1)@@ -248,62 +244,28 @@ class TemporalGuideGenerator:def process(self, rgba: np.ndarray) -> GuideFrame:current = self._small_gray(rgba)- pixels = self.width * self.heightif self.previous_gray is None:- motion = np.zeros((self.height, self.width, 2), dtype=np.float32)+ motion = self.zero_motionreset = Truescene_score = 1.0else:scene_score = float(np.mean(cv2.absdiff(current, self.previous_gray))) / 255.0reset = scene_score > 0.24if reset:- motion = np.zeros((self.height, self.width, 2), dtype=np.float32)+ motion = self.zero_motionelse:- cur_to_prev = self.dis.calc(current, self.previous_gray, None)- prev_to_cur = self.dis.calc(self.previous_gray, current, None)- yy, xx = np.mgrid[0 : self.flow_height, 0 : self.flow_width].astype(- np.float32- )- sample_x = xx + cur_to_prev[..., 0]- sample_y = yy + cur_to_prev[..., 1]- reverse = cv2.remap(- prev_to_cur,- sample_x,- sample_y,- cv2.INTER_LINEAR,- borderMode=cv2.BORDER_CONSTANT,- )- consistency = cv2.magnitude(- cur_to_prev[..., 0] + reverse[..., 0],- cur_to_prev[..., 1] + reverse[..., 1],- )- warped_previous = cv2.remap(- self.previous_gray,- sample_x,- sample_y,- cv2.INTER_LINEAR,- borderMode=cv2.BORDER_REFLECT,- )- residual = (- cv2.absdiff(current, warped_previous).astype(np.float32) / 255.0- )- invalid = np.maximum(- np.clip(consistency / 2.5, 0.0, 1.0),- np.clip(residual * 4.0, 0.0, 1.0),- )- cv2.dilate(invalid, np.ones((3, 3), np.uint8), iterations=1)-+ motion = self.dis.calc(current, self.previous_gray, None)motion = cv2.resize(- cur_to_prev,+ motion,(self.width, self.height),interpolation=cv2.INTER_LINEAR,)motion[..., 0] *= self.width / self.flow_widthmotion[..., 1] *= self.height / self.flow_height+ motion = np.ascontiguousarray(motion.astype(np.float16))self.previous_gray = current- assert motion.size == pixels * 2return GuideFrame(- motion=np.ascontiguousarray(motion.astype(np.float16)),+ motion=motion,reset=reset,scene_score=scene_score,)@@ -341,6 +303,8 @@ def convert_video(options: ConversionOptions | None = None,progress: Callable[[float, str], None] | None = None,) -> ConversionResult:+ from .prepare import prepare_runtime+options = options or ConversionOptions()source = Path(input_path).resolve()if not source.is_file():@@ -353,29 +317,46 @@ def convert_video("HDR preservation is disabled in this build because the verified DLSSNR path is ""RGBA8. HDR input is converted to SDR instead of being mislabeled as HDR.")- validate_runtime_files()+ prepared_runtime = prepare_runtime()with active_job() as controller:started = time.perf_counter()+ timings: dict[str, float] = {}job_dir: Path | None = Noneoutput: Path | None = Nonesession: DLSSFrameSession | None = None- gpu: dict | None = None- runtime_bundle: dict | None = None+ gpu: dict | None = dict(prepared_runtime.gpu)+ runtime_bundle: dict | None = prepared_runtime.runtime_bundleencoder = None- nut = None- input_container = 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)++ def record_pipeline_error(exc: BaseException) -> None:+ pipeline_stop.set()+ try:+ pipeline_errors.put_nowait(exc)+ except queue.Full:+ pass+try:- metadata = probe_video(source)+ stage_started = time.perf_counter()+ metadata = ffmpeg.probe_video(source, count_mode="metadata")if preview_frames is not None:- frame_count = min(int(metadata["frames"]), preview_frames)+ known_frames = int(metadata["frames"])+ frame_count = min(known_frames, preview_frames) if known_frames else preview_frameselif preview_seconds is not None:frame_count = ffmpeg.preview_frame_count(source, preview_seconds)else:frame_count = int(metadata["frames"])- gpu = detect_gpu()- runtime_bundle = inspect_runtime_bundle()- validate_gpu_runtime(gpu, runtime_bundle)+ if frame_count <= 0:+ exact = ffmpeg.probe_video(source, count_mode="exact")+ frame_count = int(exact["frames"])+ metadata["frames"] = frame_count+ metadata["frame_count_source"] = exact["frame_count_source"]+ timings["probe_seconds"] = time.perf_counter() - stage_startedinput_width = int(metadata["width"])input_height = int(metadata["height"])factor, mode = resolve_upscaling_mode(options.upscaling_factor)@@ -408,6 +389,35 @@ def convert_video(if progress:progress(0.01, f"Starting feature 18 on {gpu['display_name']}")+ encoder_setup: list[tuple] = []+ encoding_stage_started = time.perf_counter()++ def prepare_encoder() -> None:+ encoder_started = time.perf_counter()+ try:+ encoder_setup.append(+ ffmpeg.start_encoder(+ temp_video,+ options.codec,+ options.quality,+ controller,+ output_width,+ output_height,+ float(metadata["fps"]),+ )+ )+ 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()+ session_started = time.perf_counter()session = DLSSFrameSession(input_width=input_width,input_height=input_height,@@ -422,6 +432,17 @@ def convert_video(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_widthrender_height = session.render_heightsetup_result = session.setup_result@@ -438,48 +459,142 @@ def convert_video((encoder,- encoder_thread,+ encoder_log_thread,encoder_logs,selected_encoder,encoding_quality,- ) = ffmpeg.start_encoder(- temp_video,- options.codec,- options.quality,- controller,- output_width,- output_height,- float(metadata["fps"]),- )+ ) = encoder_setup[0]assert encoder.stdin is not None- nut = av.open(encoder.stdin, mode="w", format="nut")- input_container = av.open(str(source))- input_stream = input_container.streams.video[0]- input_stream.thread_type = "AUTO"- rate = input_stream.average_rate or metadata["rate"]- raw_stream = nut.add_stream("rawvideo", rate=rate)- raw_stream.width = output_width- raw_stream.height = output_height- raw_stream.pix_fmt = "rgba"- raw_stream.time_base = input_stream.time_base or metadata["time_base"]- guides = TemporalGuideGenerator(render_width, render_height)++ prepared_bytes = render_width * render_height * 8+ rendered_bytes = output_width * output_height * 4+ 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)+ stop_marker = object()+ producer_stats: dict[str, float | int] = {}+ writer_stats: dict[str, float | int] = {}++ 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 produce_frames() -> None:+ producer_started = time.perf_counter()+ decoded = 0+ container = None+ try:+ container = av.open(str(source))+ stream = container.streams.video[0]+ stream.thread_type = "AUTO"+ guides = TemporalGuideGenerator(render_width, render_height)+ for index, frame in enumerate(container.decode(stream)):+ if index >= frame_count or pipeline_stop.is_set():+ break+ if controller.cancel.is_set():+ raise Cancelled("Render stopped by user.")+ rgba = rotate_frame(+ frame.to_ndarray(format="rgba"), metadata["rotation"]+ )+ if rgba.shape[1] != render_width or rgba.shape[0] != render_height:+ rgba = resize_fit(rgba, render_width, render_height)+ rgba = np.ascontiguousarray(rgba, dtype=np.uint8)+ guide = guides.process(rgba)+ pts = int(frame.pts if frame.pts is not None else index)+ if not put_pipeline(+ prepared_frames, (index, rgba, guide, pts)+ ):+ return+ decoded += 1+ producer_stats["decoded_frames"] = decoded+ put_pipeline(prepared_frames, stop_marker)+ except BaseException as exc:+ record_pipeline_error(exc)+ put_pipeline(prepared_frames, stop_marker)+ finally:+ 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+ nut = None+ try:+ nut = av.open(encoder.stdin, mode="w", format="nut")+ raw_stream = nut.add_stream("rawvideo", rate=metadata["rate"])+ raw_stream.width = output_width+ raw_stream.height = output_height+ raw_stream.pix_fmt = "rgba"+ raw_stream.time_base = metadata["time_base"]+ while not pipeline_stop.is_set():+ if controller.cancel.is_set():+ raise Cancelled("Render stopped by user.")+ try:+ item = rendered_frames.get(timeout=0.1)+ except queue.Empty:+ continue+ if item is stop_marker:+ break+ processed, output_pts = item+ output_frame = av.VideoFrame.from_ndarray(processed, format="rgba")+ output_frame.pts = output_pts+ output_frame.time_base = metadata["time_base"]+ for packet in raw_stream.encode(output_frame):+ nut.mux(packet)+ written += 1+ if not pipeline_stop.is_set():+ for packet in raw_stream.encode():+ nut.mux(packet)+ nut.close()+ nut = None+ writer_stats["written_frames"] = written+ except BaseException as exc:+ record_pipeline_error(exc)+ finally:+ 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 = 0scene_resets = 0preview_pts_origin: int | None = None- for index, frame in enumerate(input_container.decode(input_stream)):- if index >= frame_count:- break+ dlss_seconds = 0.0+ last_progress_update = 0.0+ while True:if controller.cancel.is_set():raise Cancelled("Render stopped by user.")- rgba = rotate_frame(- frame.to_ndarray(format="rgba"), metadata["rotation"]- )- if rgba.shape[1] != render_width or rgba.shape[0] != render_height:- rgba = resize_fit(rgba, render_width, render_height)- rgba = np.ascontiguousarray(rgba, dtype=np.uint8)- guide = guides.process(rgba)+ 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, rgba, guide, pts = itemscene_resets += int(guide.reset and index != 0)- pts = int(frame.pts if frame.pts is not None else index)+ dlss_started = time.perf_counter()processed, out_pts = session.process(index=index,rgba=rgba,@@ -487,40 +602,50 @@ def convert_video(reset=guide.reset,pts=pts,)- out_frame = av.VideoFrame.from_ndarray(processed, format="rgba")+ dlss_seconds += time.perf_counter() - dlss_startedif is_preview:if preview_pts_origin is None:preview_pts_origin = out_pts- out_frame.pts = out_pts - preview_pts_origin- else:- out_frame.pts = out_pts- out_frame.time_base = input_stream.time_base or metadata["time_base"]- for packet in raw_stream.encode(out_frame):- nut.mux(packet)+ out_pts -= preview_pts_origin+ if not put_pipeline(rendered_frames, (processed, out_pts)):+ if not pipeline_errors.empty():+ raise pipeline_errors.get_nowait()+ raise Cancelled("Render stopped by user.")delivered += 1- if progress:+ now = time.perf_counter()+ if progress and (delivered == frame_count or now - last_progress_update >= 0.1):progress(0.04 + 0.84 * delivered / frame_count,f"DLSS 5 frame {delivered}/{frame_count}",)+ last_progress_update = nowif delivered != frame_count:raise RuntimeError(f"Decoded {delivered} frames instead of the expected {frame_count}; ""refusing an incomplete render.")- for packet in raw_stream.encode():- nut.mux(packet)- nut.close()- nut = None+ 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()+ timings["producer_seconds"] = float(producer_stats.get("seconds", 0.0))+ timings["decode_and_guide_seconds"] = timings["producer_seconds"]+ timings["dlss_seconds"] = dlss_seconds+ timings["encoder_feed_seconds"] = float(writer_stats.get("seconds", 0.0))if encoder.stdin and not encoder.stdin.closed:encoder.stdin.close()- input_container.close()- input_container = Nonesession.close()encoder_code = encoder.wait(timeout=120)- encoder_thread.join(timeout=2)+ encoder_log_thread.join(timeout=2)controller.unregister(encoder)+ timings["encoding_seconds"] = time.perf_counter() - encoding_stage_startedif encoder_code:raise RuntimeError("Video encoder failed:\n" + "\n".join(encoder_logs[-40:])@@ -536,8 +661,14 @@ def convert_video(carrier_create_result = str(feature_evidence["carrier_create_result"])if progress:progress(0.91, "Muxing original audio and metadata")- ffmpeg.final_mux(temp_video, source, output, options.container)- verified = probe_video(output)+ mux_started = time.perf_counter()+ ffmpeg.final_mux(temp_video, source, output, options.container, controller)+ timings["final_mux_seconds"] = time.perf_counter() - mux_started+ timings["muxing_seconds"] = timings["final_mux_seconds"]+ verify_started = time.perf_counter()+ verified = ffmpeg.probe_video(output, count_mode="packets")+ if verified["frames"] != delivered:+ verified = ffmpeg.probe_video(output, count_mode="exact")if verified["frames"] != delivered:raise RuntimeError(f"Output verification found {verified['frames']} frames instead of "@@ -551,6 +682,7 @@ def convert_video(f"Output verification found {verified['width']}×{verified['height']} "f"instead of {output_width}×{output_height}.")+ timings["verification_seconds"] = time.perf_counter() - verify_startedelapsed = time.perf_counter() - startedreport = {@@ -601,10 +733,8 @@ def convert_video("feature_18_confirmed": True,"carrier_create_result": carrier_create_result,"successful_neural_rendering_frames": nr_count,- "model_sha256": hashlib.sha256(- (RUNTIME / "nvngx_dlssnr.dll").read_bytes()- ).hexdigest(),- "worker_sha256": hashlib.sha256(WORKER.read_bytes()).hexdigest(),+ "model_sha256": runtime_bundle["neural_runtime"]["sha256"].lower(),+ "worker_sha256": runtime_bundle["worker"]["sha256"].lower(),"loaded_module_inventory": ["nvngx.dll (standalone worker image)","dxgi.dll (ReShade carrier)",@@ -616,7 +746,9 @@ def convert_video("native_settings": native,"elapsed_seconds": elapsed,"average_fps": delivered / elapsed,+ "timings": timings,"worker_log": session.worker_logs,+ "worker_log_dropped_lines": session.worker_log_dropped_lines,"encoder_log": encoder_logs,"dlssnr_evidence": feature_evidence["evidence"],}@@ -642,16 +774,19 @@ def convert_video()except Exception as exc:was_cancelled = controller.cancel.is_set()+ pipeline_stop.set()controller.stop()+ 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 nut is not None:- with suppress(Exception):- nut.close()- if input_container is not None:- with suppress(Exception):- input_container.close()if encoder is not None and encoder.stdin and not encoder.stdin.closed:with suppress(OSError):encoder.stdin.close()@@ -676,5 +811,6 @@ def convert_video()raise RuntimeError(f"{exc}\nDiagnostic report: {report_path}") from excfinally:+ pipeline_stop.set()if job_dir and job_dir.exists():shutil.rmtree(job_dir, ignore_errors=True)