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
Merserkd999a091b974
diff --git a/app.py b/app.pyindex 970a574..c2eb4f7 100644--- a/app.py+++ b/app.py@@ -18,10 +18,22 @@ from src.images import (take_image_preview,)from src.naming import RENAME_MODES+from src.ffmpeg import probe_nvenc_codecs, probe_video+from src.frame_interpolation import (+ ENGINE_CHOICES,+ FPS_CHOICES,+ FrameInterpolationOptions,+ choose_interpolation_plan,+ interpolate_video,+ interpolate_videos,+ probe_frame_interpolation_capabilities,+)from src.runtime import (LOGS,OUTPUTS,cancel_active_job,+ gpu_choice_label,+ validate_gpu_runtime,)from src.prepare import prepare_runtimefrom src.settings import (@@ -30,7 +42,10 @@ from src.settings import (DEFAULT_SETTINGS,QUALITY_CHOICES,UISettings,+ export_settings_preset,+ import_settings_preset,load_settings,+ preset_filename,save_settings,)from src.video import (@@ -64,7 +79,9 @@ APP_CSS = """#image-upload-list .file-preview-holder,#image-output-list .file-preview-holder,#video-upload-list .file-preview-holder,-#video-output-list .file-preview-holder {+#video-output-list .file-preview-holder,+#frame-interpolation-upload-list .file-preview-holder,+#frame-interpolation-output-list .file-preview-holder {max-height: 210px !important;overflow-x: hidden !important;overflow-y: auto !important;@@ -75,7 +92,9 @@ APP_CSS = """#image-upload-list .file-preview,#image-output-list .file-preview,#video-upload-list .file-preview,-#video-output-list .file-preview {+#video-output-list .file-preview,+#frame-interpolation-upload-list .file-preview,+#frame-interpolation-output-list .file-preview {max-height: none !important;}@@ -240,27 +259,196 @@ def persist_video_settings(return _shared_dlss_values(settings)+def persist_frame_interpolation_settings(+ target_fps: str,+ engine: str,+ codec: str,+ container: str,+ quality: str,+ rename_mode: str,+ custom_suffix: str,+) -> None:+ global _CURRENT_SETTINGS+ with _CONFIG_LOCK:+ current = _CURRENT_SETTINGS or load_settings(CONFIG_PATH)+ settings = replace(+ current,+ frame_interpolation_target_fps=target_fps,+ frame_interpolation_engine=engine,+ frame_interpolation_codec=codec,+ frame_interpolation_container=container,+ frame_interpolation_quality=quality,+ frame_interpolation_rename_mode=rename_mode,+ frame_interpolation_custom_suffix=custom_suffix,+ )+ if settings != current:+ save_settings(CONFIG_PATH, settings)+ _CURRENT_SETTINGS = settings+++def _settings_component_values(settings: UISettings) -> tuple:+ shared = _shared_dlss_values(settings)+ return (+ *shared,+ *shared,+ settings.image_format,+ settings.image_quality,+ settings.image_rename_mode,+ gr.update(+ value=settings.image_custom_suffix,+ interactive=settings.image_rename_mode == "Custom",+ ),+ settings.codec,+ settings.container,+ settings.quality,+ settings.video_rename_mode,+ gr.update(+ value=settings.video_custom_suffix,+ interactive=settings.video_rename_mode == "Custom",+ ),+ settings.frame_interpolation_target_fps,+ settings.frame_interpolation_engine,+ settings.frame_interpolation_codec,+ settings.frame_interpolation_container,+ settings.frame_interpolation_quality,+ settings.frame_interpolation_rename_mode,+ gr.update(+ value=settings.frame_interpolation_custom_suffix,+ interactive=settings.frame_interpolation_rename_mode == "Custom",+ ),+ settings.ai_gpu_uuid,+ settings.video_gpu_uuid,+ )+++def _processing_gpu_settings() -> tuple[str, str]:+ with _CONFIG_LOCK:+ settings = _CURRENT_SETTINGS or load_settings(CONFIG_PATH)+ return settings.ai_gpu_uuid, settings.video_gpu_uuid+++def _gpu_choices(prepared) -> tuple[list[tuple[str, str]], list[tuple[str, str]]]:+ automatic = [("Automatic (first compatible)", "auto")]+ ai = []+ for gpu in prepared.gpus:+ if not gpu.get("ai_compatible") or not gpu.get("adapter_luid"):+ continue+ try:+ validate_gpu_runtime(gpu, prepared.runtime_bundle)+ except RuntimeError:+ continue+ ai.append((gpu_choice_label(gpu), str(gpu["uuid"])))+ video = [+ (gpu_choice_label(gpu), str(gpu["uuid"]))+ for gpu in prepared.gpus+ if gpu.get("cuda_ordinal") is not None+ and probe_nvenc_codecs(int(gpu["cuda_ordinal"]))+ ]+ return automatic + ai, automatic + video+++def _normalize_gpu_settings(settings: UISettings, prepared) -> tuple[UISettings, str]:+ ai_choices, video_choices = _gpu_choices(prepared)+ ai_values = {value for _label, value in ai_choices}+ video_values = {value for _label, value in video_choices}+ warnings = []+ ai_uuid = settings.ai_gpu_uuid+ video_uuid = settings.video_gpu_uuid+ if ai_uuid not in ai_values:+ warnings.append("Saved AI Processing GPU is unavailable; using Automatic.")+ ai_uuid = "auto"+ if video_uuid not in video_values:+ warnings.append("Saved Video Processing GPU is unavailable; using Automatic.")+ video_uuid = "auto"+ return replace(settings, ai_gpu_uuid=ai_uuid, video_gpu_uuid=video_uuid), " ".join(warnings)+++def persist_gpu_settings(ai_gpu_uuid: str, video_gpu_uuid: str) -> str:+ global _CURRENT_SETTINGS+ prepared = prepare_runtime()+ ai_choices, video_choices = _gpu_choices(prepared)+ if ai_gpu_uuid not in {value for _label, value in ai_choices}:+ raise gr.Error("Choose an available AI Processing GPU.")+ if video_gpu_uuid not in {value for _label, value in video_choices}:+ raise gr.Error("Choose an available Video Processing GPU.")+ with _CONFIG_LOCK:+ current = _CURRENT_SETTINGS or load_settings(CONFIG_PATH)+ settings = replace(+ current, ai_gpu_uuid=ai_gpu_uuid, video_gpu_uuid=video_gpu_uuid+ )+ if settings != current:+ save_settings(CONFIG_PATH, settings)+ _CURRENT_SETTINGS = settings+ ai_name = "Automatic" if ai_gpu_uuid == "auto" else next(+ label for label, value in ai_choices if value == ai_gpu_uuid+ )+ video_name = "Automatic" if video_gpu_uuid == "auto" else next(+ label for label, value in video_choices if value == video_gpu_uuid+ )+ return f"AI Processing: {ai_name}\n\nVideo Processing: {video_name}"++def reset_saved_settings() -> tuple:global _CURRENT_SETTINGSwith _CONFIG_LOCK:save_settings(CONFIG_PATH, DEFAULT_SETTINGS)_CURRENT_SETTINGS = DEFAULT_SETTINGS- shared = _shared_dlss_values(DEFAULT_SETTINGS)- message = "All Image and Video settings were reset to defaults."+ message = "All Image, Video, and Frame Interpolation settings were reset to defaults."return (- *shared,- *shared,- DEFAULT_SETTINGS.image_format,- DEFAULT_SETTINGS.image_quality,- DEFAULT_SETTINGS.image_rename_mode,- gr.update(value=DEFAULT_SETTINGS.image_custom_suffix, interactive=False),- DEFAULT_SETTINGS.codec,- DEFAULT_SETTINGS.container,- DEFAULT_SETTINGS.quality,- DEFAULT_SETTINGS.video_rename_mode,- gr.update(value=DEFAULT_SETTINGS.video_custom_suffix, interactive=False),+ *_settings_component_values(DEFAULT_SETTINGS),message,message,+ message,+ "AI Processing and Video Processing GPU selections were reset to Automatic.",+ )+++def settings_preset_download(name: str) -> str | None:+ if not isinstance(name, str) or not name.strip():+ return None+ with _CONFIG_LOCK:+ current = _CURRENT_SETTINGS or load_settings(CONFIG_PATH)+ try:+ path = export_settings_preset(name, current)+ except ValueError:+ return None+ return str(path)+++def settings_preset_export_status(name: str) -> str:+ try:+ filename = preset_filename(name)+ except ValueError as exc:+ return f"Export failed: {exc}"+ return f"Exported preset {name.strip()!r} as {filename}."+++def apply_settings_preset(+ uploaded_path: str | None, current_name: str+) -> tuple:+ global _CURRENT_SETTINGS+ with _CONFIG_LOCK:+ current = _CURRENT_SETTINGS or load_settings(CONFIG_PATH)+ try:+ if not uploaded_path:+ raise ValueError("Choose a JSON preset file before importing.")+ name, imported = import_settings_preset(uploaded_path, current)+ imported, gpu_warning = _normalize_gpu_settings(+ imported, prepare_runtime()+ )+ save_settings(CONFIG_PATH, imported)+ except (OSError, ValueError) as exc:+ return (+ current_name,+ *_settings_component_values(current),+ f"Import failed: {exc}",+ )+ _CURRENT_SETTINGS = imported+ return (+ name,+ *_settings_component_values(imported),+ f"Imported preset {name!r}; all tabs and saved startup settings were updated."+ + (f" {gpu_warning}" if gpu_warning else ""),)@@ -285,7 +473,10 @@ def _process_video(if not input_path:raise gr.Error("Choose a video first.")is_preview = preview_seconds is not None or preview_frames is not None+ ai_gpu_uuid, video_gpu_uuid = _processing_gpu_settings()options = ConversionOptions(+ ai_gpu_uuid=ai_gpu_uuid,+ video_gpu_uuid=video_gpu_uuid,nr_preset=nr_preset,nr_style=nr_style,nr_intensity=nr_intensity,@@ -385,6 +576,178 @@ def update_video_preview_mode(paths: list[str] | str | None):)+def frame_interpolation_capability_text() -> str:+ ai_gpu_uuid, _video_gpu_uuid = _processing_gpu_settings()+ capabilities = probe_frame_interpolation_capabilities(ai_gpu_uuid)+ hags = "Enabled" if capabilities.hags_enabled else "Disabled"+ native = (+ f"{capabilities.native_multiplier}× "+ f"({capabilities.native_generated_frame_max} generated frame per evaluation)"+ )+ cascade = "Available" if capabilities.cascade_available else "Unavailable"+ state = "Ready" if capabilities.available else "Unavailable"+ detail = f"\n{capabilities.detail}" if capabilities.detail else ""+ return (+ f"{state} — GPU: {capabilities.gpu} | Driver: {capabilities.driver} | "+ f"HAGS: {hags}\nNative maximum: {native} | Experimental cascade: {cascade} | "+ f"DLSSG runtime: {capabilities.runtime_version}{detail}"+ )+++def describe_frame_interpolation_plan(+ paths: list[str] | str | None,+ target_fps: str,+ engine: str,+) -> str:+ selected = first_video_path(paths)+ if not selected:+ return "Choose a video to preflight its DLSSG path and temporal precision."+ try:+ metadata = probe_video(selected, count_mode="metadata")+ ai_gpu_uuid, _video_gpu_uuid = _processing_gpu_settings()+ capabilities = probe_frame_interpolation_capabilities(ai_gpu_uuid)+ plan = choose_interpolation_plan(+ metadata["rate"],+ FrameInterpolationOptions(target_fps=target_fps).target_rate,+ engine,+ capabilities.native_multiplier,+ cfr=bool(metadata.get("cfr", True)),+ )+ if plan.cascade_stages:+ precision = (+ f"≤ {float(plan.maximum_temporal_error) * 1000:.3f} ms "+ f"(1/{2 * plan.grid_multiplier} source-frame interval)"+ )+ elif plan.path == "Native DLSSG":+ precision = "Exact native temporal grid"+ else:+ precision = "Nearest real source frame"+ return (+ f"{Path(selected).name}: {metadata['rate']} FPS → {target_fps} FPS | "+ f"Path: {plan.path} | Cascade stages: {plan.cascade_stages} | "+ f"Internal grid: {plan.grid_multiplier}× | Precision: {precision}"+ )+ except Exception as exc:+ return f"Preflight: {exc}"+++def update_frame_interpolation_preview_mode(+ paths: list[str] | str | None,+ target_fps: str,+ engine: str,+):+ normalized = _normalize_video_paths(paths)+ single = len(normalized) == 1+ return (+ gr.update(value=normalized[0] if single else None, visible=single),+ gr.update(value=None, visible=single),+ gr.update(visible=single),+ describe_frame_interpolation_plan(paths, target_fps, engine),+ )+++def render_frame_interpolation_batch(+ input_paths: list[str] | str | None,+ target_fps: str,+ engine: str,+ codec: str,+ container: str,+ quality: str,+ rename_mode: str,+ custom_suffix: str,+ progress=gr.Progress(track_tqdm=False),+):+ paths = _normalize_video_paths(input_paths)+ if not paths:+ raise gr.Error("Choose at least one video first.")+ options = FrameInterpolationOptions(+ ai_gpu_uuid=_processing_gpu_settings()[0],+ video_gpu_uuid=_processing_gpu_settings()[1],+ target_fps=target_fps,+ engine=engine,+ codec=codec,+ container=container,+ quality=quality,+ rename_mode=rename_mode,+ custom_suffix=custom_suffix,+ )++ def report(value: float, message: str) -> None:+ progress(value, desc=message)++ try:+ result = interpolate_videos(paths, options, report)+ except Exception as exc:+ traceback.print_exc()+ raise gr.Error(str(exc)) from exc+ ordered: list[tuple[int, list[str]]] = []+ for item in result.successes:+ value = item.result+ details = (+ f"{value.output_frames} frames; {value.selected_path}; "+ f"native {value.native_multiplier}×; cascade stages {value.cascade_stages}; "+ f"copied {value.copied_frames}, DLSSG {value.generated_frames}, "+ f"cuts {value.scene_cuts}; report: {value.report_path}"+ )+ ordered.append(+ (item.index, [Path(item.input_path).name, "Complete", Path(value.output_path).name, details])+ )+ for item in result.failures:+ state = "Skipped" if item.error == "Cancelled before rendering." else (+ "Cancelled" if item.cancelled else "Failed"+ )+ ordered.append((item.index, [Path(item.input_path).name, state, "", item.error]))+ rows = [row for _index, row in sorted(ordered, key=lambda entry: entry[0])]+ files = [item.result.output_path for item in result.successes]+ preview = None+ if len(paths) == 1 and result.successes and Path(files[0]).suffix.lower() == ".mp4":+ preview = files[0]+ status = (+ f"{'Cancelled' if result.cancelled else 'Complete'}: "+ f"{len(result.successes)} completed, {len(result.failures)} failed/cancelled. "+ f"Batch manifest: {result.manifest_path}"+ )+ return gr.update(value=preview, visible=len(paths) == 1), files, rows, status+++def preview_frame_interpolation(+ input_paths: list[str] | str | None,+ target_fps: str,+ engine: str,+ codec: str,+ container: str,+ quality: str,+ progress=gr.Progress(track_tqdm=False),+):+ selected = first_video_path(input_paths)+ if not selected:+ raise gr.Error("Choose one video first.")+ options = FrameInterpolationOptions(+ ai_gpu_uuid=_processing_gpu_settings()[0],+ video_gpu_uuid=_processing_gpu_settings()[1],+ target_fps=target_fps,+ engine=engine,+ codec="H.264",+ container="MP4",+ quality=quality,+ preview_seconds=PREVIEW_SECONDS,+ )+ try:+ result = interpolate_video(+ selected,+ options,+ lambda value, message: progress(value, desc=message),+ )+ except Exception as exc:+ traceback.print_exc()+ raise gr.Error(str(exc)) from exc+ return result.output_path, (+ f"Preview complete: {result.output_frames} frames, {result.selected_path}, "+ f"{result.cascade_stages} cascade stage(s), {result.generated_frames} DLSSG-selected "+ f"frames in {result.elapsed_seconds:.1f}s. Report: {result.report_path}"+ )++def render_video_batch(input_paths: list[str] | str | None,nr_preset: str,@@ -407,6 +770,8 @@ def render_video_batch(if not paths:raise gr.Error("Choose at least one video first.")options = ConversionOptions(+ ai_gpu_uuid=_processing_gpu_settings()[0],+ video_gpu_uuid=_processing_gpu_settings()[1],nr_preset=nr_preset,nr_style=nr_style,nr_intensity=nr_intensity,@@ -573,6 +938,7 @@ def render_image_batch(if isinstance(input_paths, str):input_paths = [input_paths]options = ImageConversionOptions(+ ai_gpu_uuid=_processing_gpu_settings()[0],nr_preset=nr_preset,nr_style=nr_style,nr_intensity=nr_intensity,@@ -684,8 +1050,13 @@ def build_dlss_model_control(settings: UISettings):def build_app() -> gr.Blocks:"""Build the UI from the cached settings without rewriting configuration."""global _CURRENT_SETTINGS+ prepared = prepare_runtime()settings = _CURRENT_SETTINGS or load_settings(CONFIG_PATH)+ settings, gpu_warning = _normalize_gpu_settings(settings, prepared)+ if settings != (_CURRENT_SETTINGS or load_settings(CONFIG_PATH)):+ save_settings(CONFIG_PATH, settings)_CURRENT_SETTINGS = settings+ ai_gpu_choices, video_gpu_choices = _gpu_choices(prepared)upload_types = ["image", ".svg", ".heic", ".heif", *sorted(RAW_EXTENSIONS)]with gr.Blocks(title="DLSS 5 Visual Enhancer") as demo:@@ -893,6 +1264,181 @@ def build_app() -> gr.Blocks:wrap=True,)+ with gr.Tab("Frame Interpolation", id="frame-interpolation"):+ with gr.Row():+ with gr.Column(scale=3):+ frame_interpolation_sources = gr.File(+ label="Input video(s)",+ file_count="multiple",+ file_types=["video"],+ type="filepath",+ allow_reordering=True,+ elem_id="frame-interpolation-upload-list",+ )+ frame_interpolation_input_preview = gr.Video(+ label="Input video preview",+ interactive=False,+ visible=False,+ )+ with gr.Accordion("DLSS Frame Generation Settings", open=True):+ with gr.Row():+ frame_interpolation_target_fps = gr.Dropdown(+ FPS_CHOICES,+ value=settings.frame_interpolation_target_fps,+ label="Output FPS",+ info="Fractional choices use exact 1001-based rates.",+ )+ frame_interpolation_engine = gr.Radio(+ ENGINE_CHOICES,+ value=settings.frame_interpolation_engine,+ label="DLSS engine",+ info=(+ "Auto uses a supported exact native grid, then the "+ "2× cascade when required."+ ),+ )+ frame_interpolation_capabilities = gr.Textbox(+ value=frame_interpolation_capability_text(),+ label="GPU / HAGS / driver / DLSSG capability",+ interactive=False,+ lines=3,+ )+ frame_interpolation_plan = gr.Textbox(+ value=(+ "Choose a video to preflight its DLSSG path and temporal "+ "precision."+ ),+ label="Per-file interpolation plan",+ interactive=False,+ lines=2,+ )+ frame_interpolation_quality = gr.Radio(+ QUALITY_CHOICES,+ value=settings.frame_interpolation_quality,+ label="Encoding quality",+ info="Auto uses output resolution, selected FPS, and codec.",+ )+ with gr.Row():+ frame_interpolation_codec = gr.Dropdown(+ CODEC_CHOICES,+ value=settings.frame_interpolation_codec,+ label="Video codec",+ )+ frame_interpolation_container = gr.Dropdown(+ CONTAINER_CHOICES,+ value=settings.frame_interpolation_container,+ label="Container",+ )+ with gr.Row():+ frame_interpolation_rename_mode = gr.Radio(+ RENAME_MODES,+ value=settings.frame_interpolation_rename_mode,+ label="Rename",+ info=(+ "Auto adds a DLSSFG timestamp; Copy keeps the original base "+ "name; Custom appends your suffix."+ ),+ )+ frame_interpolation_custom_suffix = gr.Textbox(+ value=settings.frame_interpolation_custom_suffix,+ label="Custom suffix",+ placeholder="_DLSSFG",+ interactive=(+ settings.frame_interpolation_rename_mode == "Custom"+ ),+ )+ gr.Markdown(+ "Pure NVIDIA DLSSG: CPU optical flow supplies guide vectors only; "+ "every invented image is returned by signed DLSSG 310.7. HDR "+ "PQ/HLG input is rejected in v1. Maximum output/source rate is 6×."+ )+ with gr.Row():+ frame_interpolation_preview = gr.Button(+ "Preview 3 sec", visible=False+ )+ frame_interpolation_render = gr.Button(+ "Interpolate video(s)", variant="primary"+ )+ frame_interpolation_stop = gr.Button("Stop", variant="stop")+ frame_interpolation_reset = gr.Button("Reset settings")+ frame_interpolation_status = gr.Textbox(+ label="Status", interactive=False+ )+ with gr.Column(scale=3):+ frame_interpolation_output_video = gr.Video(+ label="Interpolated output",+ interactive=False,+ visible=False,+ )+ frame_interpolation_output_files = gr.File(+ label="Interpolated video files",+ file_count="multiple",+ interactive=False,+ elem_id="frame-interpolation-output-list",+ )+ frame_interpolation_results = gr.Dataframe(+ headers=["Input", "Result", "Output", "Details"],+ datatype=["str", "str", "str", "str"],+ interactive=False,+ label="Batch results",+ wrap=True,+ )++ with gr.Tab("Settings", id="settings"):+ gr.Markdown(+ "## GPU Selection\n"+ "AI Processing controls DLSS and Frame Generation. Video Processing "+ "controls FFmpeg NVENC only; ProRes and mux-only work remain CPU-based."+ )+ with gr.Row():+ ai_gpu_selector = gr.Dropdown(+ choices=ai_gpu_choices,+ value=settings.ai_gpu_uuid,+ label="AI Processing GPU",+ info="Used for every DLSS Neural Rendering and Frame Generation operation.",+ )+ video_gpu_selector = gr.Dropdown(+ choices=video_gpu_choices,+ value=settings.video_gpu_uuid,+ label="Video Processing GPU",+ info="Used for FFmpeg H.264, HEVC, and AV1 NVENC encoding only.",+ )+ gpu_status = gr.Markdown(+ gpu_warning or "GPU selections are ready.",+ elem_id="gpu-selection-status",+ )+ gr.Markdown(+ "## Settings Presets\n"+ "Export every adjustable option from the Image, Video, and Frame "+ "Interpolation tabs, or import a preset to apply it everywhere."+ )+ with gr.Row():+ preset_name = gr.Textbox(+ label="Preset name",+ placeholder="Cinematic 2",+ info="The exported file uses this name; the original name is stored in JSON.",+ scale=3,+ )+ preset_export = gr.DownloadButton(+ "Export preset",+ value=settings_preset_download,+ inputs=preset_name,+ variant="primary",+ scale=1,+ )+ preset_import = gr.UploadButton(+ "Import preset",+ file_count="single",+ file_types=[".json"],+ type="filepath",+ variant="primary",+ scale=1,+ )+ preset_status = gr.Markdown(+ "",+ elem_id="preset-status",+ )+image_inputs = [image_sources,*image_neural,@@ -937,6 +1483,57 @@ def build_app() -> gr.Blocks:video_rename_mode,video_custom_suffix,]+ frame_interpolation_inputs = [+ frame_interpolation_sources,+ frame_interpolation_target_fps,+ frame_interpolation_engine,+ frame_interpolation_codec,+ frame_interpolation_container,+ frame_interpolation_quality,+ frame_interpolation_rename_mode,+ frame_interpolation_custom_suffix,+ ]+ frame_interpolation_preview_inputs = [+ frame_interpolation_sources,+ frame_interpolation_target_fps,+ frame_interpolation_engine,+ frame_interpolation_codec,+ frame_interpolation_container,+ frame_interpolation_quality,+ ]+ frame_interpolation_settings_inputs = [+ frame_interpolation_target_fps,+ frame_interpolation_engine,+ frame_interpolation_codec,+ frame_interpolation_container,+ frame_interpolation_quality,+ frame_interpolation_rename_mode,+ frame_interpolation_custom_suffix,+ ]+ settings_component_outputs = [+ *image_neural,+ image_model_preset,+ *video_neural,+ video_model_preset,+ image_format,+ image_quality,+ image_rename_mode,+ image_custom_suffix,+ video_codec,+ video_container,+ video_quality,+ video_rename_mode,+ video_custom_suffix,+ frame_interpolation_target_fps,+ frame_interpolation_engine,+ frame_interpolation_codec,+ frame_interpolation_container,+ frame_interpolation_quality,+ frame_interpolation_rename_mode,+ frame_interpolation_custom_suffix,+ ai_gpu_selector,+ video_gpu_selector,+ ]image_sources.change(preview_input_images,@@ -957,6 +1554,22 @@ def build_app() -> gr.Blocks:queue=False,show_progress="hidden",)+ frame_interpolation_sources.change(+ update_frame_interpolation_preview_mode,+ inputs=[+ frame_interpolation_sources,+ frame_interpolation_target_fps,+ frame_interpolation_engine,+ ],+ outputs=[+ frame_interpolation_input_preview,+ frame_interpolation_output_video,+ frame_interpolation_preview,+ frame_interpolation_plan,+ ],+ queue=False,+ show_progress="hidden",+ )image_rename_mode.change(rename_suffix_update,inputs=image_rename_mode,@@ -969,6 +1582,24 @@ def build_app() -> gr.Blocks:outputs=video_custom_suffix,queue=False,)+ frame_interpolation_rename_mode.change(+ rename_suffix_update,+ inputs=frame_interpolation_rename_mode,+ outputs=frame_interpolation_custom_suffix,+ queue=False,+ )+ for component in [frame_interpolation_target_fps, frame_interpolation_engine]:+ component.change(+ describe_frame_interpolation_plan,+ inputs=[+ frame_interpolation_sources,+ frame_interpolation_target_fps,+ frame_interpolation_engine,+ ],+ outputs=frame_interpolation_plan,+ queue=False,+ show_progress="hidden",+ )for component in image_settings_inputs:component.input(persist_image_settings,@@ -983,6 +1614,69 @@ def build_app() -> gr.Blocks:outputs=[*image_neural, image_model_preset],queue=False,)+ for component in frame_interpolation_settings_inputs:+ component.input(+ persist_frame_interpolation_settings,+ inputs=frame_interpolation_settings_inputs,+ queue=False,+ )++ preset_export.click(+ settings_preset_export_status,+ inputs=preset_name,+ outputs=preset_status,+ queue=False,+ )+ preset_import_event = preset_import.upload(+ apply_settings_preset,+ inputs=[preset_import, preset_name],+ outputs=[preset_name, *settings_component_outputs, preset_status],+ queue=False,+ )+ preset_import_event.then(+ persist_gpu_settings,+ inputs=[ai_gpu_selector, video_gpu_selector],+ outputs=gpu_status,+ queue=False,+ ).then(+ frame_interpolation_capability_text,+ outputs=frame_interpolation_capabilities,+ queue=False,+ show_progress="hidden",+ ).then(+ describe_frame_interpolation_plan,+ inputs=[+ frame_interpolation_sources,+ frame_interpolation_target_fps,+ frame_interpolation_engine,+ ],+ outputs=frame_interpolation_plan,+ queue=False,+ show_progress="hidden",+ )++ for selector in [ai_gpu_selector, video_gpu_selector]:+ selector.input(+ persist_gpu_settings,+ inputs=[ai_gpu_selector, video_gpu_selector],+ outputs=gpu_status,+ queue=False,+ ).then(+ frame_interpolation_capability_text,+ outputs=frame_interpolation_capabilities,+ queue=False,+ show_progress="hidden",+ ).then(+ describe_frame_interpolation_plan,+ inputs=[+ frame_interpolation_sources,+ frame_interpolation_target_fps,+ frame_interpolation_engine,+ ],+ outputs=frame_interpolation_plan,+ queue=False,+ show_progress="hidden",+ )image_render.click(render_image_batch,@@ -1018,25 +1712,39 @@ def build_app() -> gr.Blocks:)video_stop.click(cancel_active_job, outputs=video_status, queue=False)+ frame_interpolation_render.click(+ render_frame_interpolation_batch,+ inputs=frame_interpolation_inputs,+ outputs=[+ frame_interpolation_output_video,+ frame_interpolation_output_files,+ frame_interpolation_results,+ frame_interpolation_status,+ ],+ concurrency_limit=1,+ )+ frame_interpolation_preview.click(+ preview_frame_interpolation,+ inputs=frame_interpolation_preview_inputs,+ outputs=[frame_interpolation_output_video, frame_interpolation_status],+ concurrency_limit=1,+ )+ frame_interpolation_stop.click(+ cancel_active_job, outputs=frame_interpolation_status, queue=False+ )+reset_outputs = [- *image_neural,- image_model_preset,- *video_neural,- video_model_preset,- image_format,- image_quality,- image_rename_mode,- image_custom_suffix,- video_codec,- video_container,- video_quality,- video_rename_mode,- video_custom_suffix,+ *settings_component_outputs,image_status,video_status,+ frame_interpolation_status,+ gpu_status,]image_reset.click(reset_saved_settings, outputs=reset_outputs, queue=False)video_reset.click(reset_saved_settings, outputs=reset_outputs, queue=False)+ frame_interpolation_reset.click(+ reset_saved_settings, outputs=reset_outputs, queue=False+ )return demodiff --git a/src/__init__.py b/src/__init__.pyindex 350ba42..f9e5538 100644--- a/src/__init__.py+++ b/src/__init__.py@@ -10,6 +10,15 @@ from .images import (convert_images,probe_image,)+from .frame_interpolation import (+ FrameInterpolationBatchResult,+ FrameInterpolationCapabilities,+ FrameInterpolationOptions,+ FrameInterpolationResult,+ interpolate_video,+ interpolate_videos,+ probe_frame_interpolation_capabilities,+)from .video import (ConversionOptions,ConversionResult,@@ -30,10 +39,17 @@ __all__ = ["ImageConversionOptions","ImageConversionResult","ImageConversionFailure",+ "FrameInterpolationBatchResult",+ "FrameInterpolationCapabilities",+ "FrameInterpolationOptions",+ "FrameInterpolationResult","convert_image","convert_images","convert_video","convert_videos","probe_image","probe_video",+ "interpolate_video",+ "interpolate_videos",+ "probe_frame_interpolation_capabilities",]diff --git a/src/ffmpeg.py b/src/ffmpeg.pyindex e22623a..7e25124 100644--- a/src/ffmpeg.py+++ b/src/ffmpeg.py@@ -147,8 +147,17 @@ def probe_video(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"+ average_rate_text = stream.get("avg_frame_rate") or "0/0"+ nominal_rate_text = stream.get("r_frame_rate") or "0/0"+ rate_text = average_rate_text if average_rate_text != "0/0" else nominal_rate_text+ if rate_text == "0/0":+ rate_text = "30/1"rate = Fraction(rate_text) if rate_text != "0/0" else Fraction(30, 1)+ nominal_rate = (+ Fraction(nominal_rate_text)+ if nominal_rate_text != "0/0"+ else rate+ )transfer = stream.get("color_transfer") or "unknown"return {"width": width,@@ -160,6 +169,8 @@ def probe_video("frame_count_source": frame_count_source,"fps": float(rate),"rate": rate,+ "nominal_rate": nominal_rate,+ "cfr": rate == nominal_rate,"time_base": Fraction(stream.get("time_base") or "1/1000"),"duration": float((data.get("format") or {}).get("duration") or stream.get("duration") or 0@@ -171,8 +182,11 @@ def probe_video(}-@lru_cache(maxsize=64)-def _encoder_probe(codec: str, width: int, height: int) -> bool:+@lru_cache(maxsize=256)+def _encoder_probe(+ codec: str, width: int, height: int, gpu_ordinal: int | None = None+) -> bool:+ gpu_args = ["-gpu", str(gpu_ordinal)] if gpu_ordinal is not None else []command = [str(FFMPEG),"-v",@@ -185,6 +199,7 @@ def _encoder_probe(codec: str, width: int, height: int) -> bool:"1","-c:v",codec,+ *gpu_args,"-f","null","-",@@ -199,12 +214,62 @@ def _encoder_probe(codec: str, width: int, height: int) -> bool:)+_NVENC_CODECS = {+ "H.264": "h264_nvenc",+ "HEVC": "hevc_nvenc",+ "AV1": "av1_nvenc",+}+++def probe_nvenc_codecs(gpu_ordinal: int) -> tuple[str, ...]:+ """Return user-facing codecs that can initialize NVENC on one CUDA device."""+ return tuple(+ codec+ for codec, encoder in _NVENC_CODECS.items()+ if _encoder_probe(encoder, 256, 256, int(gpu_ordinal))+ )+++def resolve_video_gpu(+ gpus: tuple[dict, ...],+ gpu_uuid: str,+ codec: str,+ width: int,+ height: int,+) -> dict | None:+ """Resolve a stable UUID to a device that supports the requested NVENC codec."""+ if codec == "ProRes Proxy":+ return None+ try:+ encoder = _NVENC_CODECS[codec]+ except KeyError as exc:+ raise ValueError(f"Unknown video codec: {codec!r}.") from exc+ candidates = [gpu for gpu in gpus if gpu.get("cuda_ordinal") is not None]+ if gpu_uuid != "auto":+ candidates = [gpu for gpu in candidates if gpu.get("uuid") == gpu_uuid]+ if not candidates:+ raise RuntimeError("The selected Video Processing GPU is unavailable.")+ for gpu in candidates:+ ordinal = int(gpu["cuda_ordinal"])+ if _encoder_probe(encoder, width, height, ordinal):+ selected = dict(gpu)+ selected["nvenc_codec"] = encoder+ return selected+ selection = "selected GPU" if gpu_uuid != "auto" else "available NVIDIA GPUs"+ raise RuntimeError(+ f"{codec} NVENC cannot encode the requested {width}×{height} output on the "+ f"{selection}. Choose another Video Processing GPU, codec, or output size."+ )++def _codec_command(codec: str,quality_name: str,width: int,height: int,fps: float,+ gpu_ordinal: int | None = None,+ require_nvenc: bool = False,) -> tuple[list[str], str, dict]:quality = resolve_encoding_quality(quality_name, codec, width, height, fps)if codec == "ProRes Proxy":@@ -220,12 +285,14 @@ def _codec_command(bitrate = f"{quality['target_bitrate_kbps']}k"nvenc_quality = ["-rc", "vbr", "-b:v", bitrate]software_quality = ["-b:v", bitrate]+ gpu_args = ["-gpu", str(gpu_ordinal)] if gpu_ordinal is not None else []if codec == "H.264":- if _encoder_probe("h264_nvenc", width, height):+ if _encoder_probe("h264_nvenc", width, height, gpu_ordinal):return (["-c:v","h264_nvenc",+ *gpu_args,"-preset","p6","-tune",@@ -237,17 +304,22 @@ def _codec_command("h264_nvenc",quality,)+ if require_nvenc:+ raise RuntimeError(+ f"H.264 NVENC cannot encode {width}×{height} on the selected Video Processing GPU."+ )return (["-c:v", "libx264", "-preset", "slow", *software_quality, "-pix_fmt", "yuv420p"],"libx264",quality,)if codec == "HEVC":- if _encoder_probe("hevc_nvenc", width, height):+ if _encoder_probe("hevc_nvenc", width, height, gpu_ordinal):return (["-c:v","hevc_nvenc",+ *gpu_args,"-preset","p6","-tune",@@ -259,6 +331,10 @@ def _codec_command("hevc_nvenc",quality,)+ if require_nvenc:+ raise RuntimeError(+ f"HEVC NVENC cannot encode {width}×{height} on the selected Video Processing GPU."+ )return (["-c:v", "libx265", "-preset", "slow", *software_quality, "-pix_fmt", "yuv420p"],"libx265",@@ -266,13 +342,16 @@ def _codec_command()if codec != "AV1":raise ValueError(f"Unknown video codec: {codec!r}.")- if not _encoder_probe("av1_nvenc", width, height):+ if not _encoder_probe("av1_nvenc", width, height, gpu_ordinal):raise RuntimeError(f"AV1 NVENC cannot encode the requested {width}×{height} output on this GPU/driver. ""Choose H.264/HEVC or a lower upscaling factor.")return (- ["-c:v", "av1_nvenc", "-preset", "p6", *nvenc_quality, "-pix_fmt", "yuv420p"],+ [+ "-c:v", "av1_nvenc", *gpu_args, "-preset", "p6", *nvenc_quality,+ "-pix_fmt", "yuv420p",+ ],"av1_nvenc",quality,)@@ -286,9 +365,11 @@ def start_encoder(width: int,height: int,fps: float,+ gpu_ordinal: int | None = None,+ require_nvenc: bool = False,):codec_args, selected, quality = _codec_command(- codec, quality_name, width, height, fps+ codec, quality_name, width, height, fps, gpu_ordinal, require_nvenc)command = [str(FFMPEG),@@ -361,6 +442,7 @@ def final_mux(output: Path,container: str,controller: JobController | None = None,+ preserve_supported_subtitles: bool = False,) -> None:duration = _probe_rendered_duration(temp_video)if container == "MKV":@@ -378,6 +460,31 @@ def final_mux("-movflags","+faststart",]+ if preserve_supported_subtitles:+ subtitle_data = _run_json(+ [+ str(FFPROBE),+ "-v",+ "error",+ "-select_streams",+ "s",+ "-show_entries",+ "stream=index,codec_name",+ "-of",+ "json",+ str(source),+ ]+ )+ supported_text = {"ass", "ssa", "subrip", "mov_text", "webvtt", "text"}+ subtitle_indices = [+ int(stream["index"])+ for stream in subtitle_data.get("streams") or []+ if stream.get("codec_name") in supported_text+ ]+ for stream_index in subtitle_indices:+ maps.extend(["-map", f"1:{stream_index}"])+ if subtitle_indices:+ streams.extend(["-c:s", "mov_text"])command = [str(FFMPEG),"-hide_banner",diff --git a/src/frame_interpolation/README.md b/src/frame_interpolation/README.mdnew file mode 100644index 0000000..185a337--- /dev/null+++ b/src/frame_interpolation/README.md@@ -0,0 +1,22 @@+# Frame Interpolation runtime++This feature uses NVIDIA DLSS Frame Generation directly through D3D12 NGX. The+signed `nvngx_dlssg.dll` 310.7 runtime is isolated under+`bin/runtime/frame_interpolation/dlssg`; `manifest.json` pins its SHA-256 and the+worker never changes `DLSSG.MultiFrameCountMax`.++On an RTX 40 GPU, a worker session asks for exactly one generated frame (2×).+Experimental 4× and 8× grids use two or three independent, sequential 2×+sessions. Output rates up to 6× are sampled from that raw dyadic grid with exact+rational presentation timestamps. Intermediate images are never encoded.++Decoded video does not contain engine depth or motion vectors. A planar SDR depth+buffer and CUDA-free OpenCV DIS optical-flow guides are supplied to DLSSG. Those+guides do not synthesize images; every generated image comes from the signed+NVIDIA runtime. Hard cuts and timestamp discontinuities reset every downstream+history. PQ and HLG input is rejected.++The NVIDIA Optical Flow SDK 5.0 DirectX headers and redistributable are not+silently downloaded because NVIDIA distributes them behind a developer-account+license gate. No CUDA, PyTorch, ONNX, RIFE, FSR FG, XeSS FG, DLSS Enabler, or+OptiScaler dependency is used.diff --git a/src/frame_interpolation/__init__.py b/src/frame_interpolation/__init__.pynew file mode 100644index 0000000..5139f91--- /dev/null+++ b/src/frame_interpolation/__init__.py@@ -0,0 +1,42 @@+from .capabilities import probe_frame_interpolation_capabilities+from .models import (+ ENGINE_CHOICES,+ FPS_CHOICES,+ FPS_RATES,+ FrameInterpolationBatchResult,+ FrameInterpolationCapabilities,+ FrameInterpolationOptions,+ FrameInterpolationResult,+ resolve_target_rate,+)+from .scheduler import choose_interpolation_plan, output_frame_count, select_grid_timestamps+++def interpolate_video(*args, **kwargs):+ from .pipeline import interpolate_video as implementation++ return implementation(*args, **kwargs)+++def interpolate_videos(*args, **kwargs):+ from .pipeline import interpolate_videos as implementation++ return implementation(*args, **kwargs)+++__all__ = [+ "ENGINE_CHOICES",+ "FPS_CHOICES",+ "FPS_RATES",+ "FrameInterpolationBatchResult",+ "FrameInterpolationCapabilities",+ "FrameInterpolationOptions",+ "FrameInterpolationResult",+ "choose_interpolation_plan",+ "interpolate_video",+ "interpolate_videos",+ "output_frame_count",+ "probe_frame_interpolation_capabilities",+ "resolve_target_rate",+ "select_grid_timestamps",+]diff --git a/src/frame_interpolation/capabilities.py b/src/frame_interpolation/capabilities.pynew file mode 100644index 0000000..788f333--- /dev/null+++ b/src/frame_interpolation/capabilities.py@@ -0,0 +1,159 @@+from __future__ import annotations++import hashlib+import json+import os+import subprocess+from functools import lru_cache+from pathlib import Path++from ..runtime import ROOT, detect_gpu+from .models import FrameInterpolationCapabilities+++RUNTIME_DIR = ROOT / "bin" / "runtime" / "frame_interpolation" / "dlssg"+DLSSG_RUNTIME = RUNTIME_DIR / "nvngx_dlssg.dll"+DLSSG_WORKER = RUNTIME_DIR / "dlssg-worker.exe"+MANIFEST = RUNTIME_DIR / "manifest.json"+EXPECTED_RUNTIME_SHA256 = "135EAF0733C1E37381A8C28ABCF7A862404A54132B81787C04E35D09EFC5E36F"+EXPECTED_WORKER_SHA256 = "8A747F9ED613842D5B8B34A811AD43BC1A9466540E2E5A0C8EF4005F0DB9E384"+++def _sha256(path: Path) -> str:+ digest = hashlib.sha256()+ with path.open("rb") as stream:+ for block in iter(lambda: stream.read(1024 * 1024), b""):+ digest.update(block)+ return digest.hexdigest().upper()+++def _hags_enabled() -> bool:+ if os.name != "nt":+ return False+ try:+ import winreg++ with winreg.OpenKey(+ winreg.HKEY_LOCAL_MACHINE,+ r"SYSTEM\CurrentControlSet\Control\GraphicsDrivers",+ ) as key:+ value, _kind = winreg.QueryValueEx(key, "HwSchMode")+ return int(value) == 2+ except (OSError, ValueError):+ return False+++def _authenticode_status(path: Path) -> str:+ if os.name != "nt":+ return "Unavailable"+ escaped = str(path.resolve()).replace("'", "''")+ try:+ process = subprocess.run(+ [+ "powershell.exe",+ "-NoProfile",+ "-NonInteractive",+ "-Command",+ "Import-Module \"$env:WINDIR\\System32\\WindowsPowerShell\\v1.0\\Modules\\"+ "Microsoft.PowerShell.Security\\Microsoft.PowerShell.Security.psd1\"; "+ f"[string](Get-AuthenticodeSignature -LiteralPath '{escaped}').Status",+ ],+ capture_output=True,+ text=True,+ encoding="utf-8",+ errors="replace",+ timeout=15,+ )+ except (OSError, subprocess.TimeoutExpired):+ return "Unavailable"+ return process.stdout.strip() if process.returncode == 0 else "Unavailable"+++def _probe_worker(adapter_luid: str | None = None) -> dict:+ if not DLSSG_WORKER.is_file():+ raise RuntimeError(f"DLSSG worker is missing: {DLSSG_WORKER}")+ command = [str(DLSSG_WORKER), "--probe"]+ if adapter_luid:+ command.extend(["--adapter-luid", adapter_luid])+ process = subprocess.run(+ command,+ cwd=str(RUNTIME_DIR),+ capture_output=True,+ text=True,+ encoding="utf-8",+ errors="replace",+ timeout=45,+ )+ if process.returncode:+ detail = process.stderr.strip() or process.stdout.strip()+ raise RuntimeError(detail or f"DLSSG capability probe exited with {process.returncode}.")+ lines = [line for line in process.stdout.splitlines() if line.strip()]+ if not lines:+ raise RuntimeError("DLSSG capability probe returned no result.")+ return json.loads(lines[-1])+++@lru_cache(maxsize=32)+def probe_frame_interpolation_capabilities(+ ai_gpu_uuid: str = "auto",+) -> FrameInterpolationCapabilities:+ gpu = detect_gpu(ai_gpu_uuid)+ gpu_name = str(gpu.get("display_name") or gpu.get("name") or "NVIDIA RTX GPU")+ driver = str(gpu.get("driver") or "unknown")+ hags = _hags_enabled()+ if not DLSSG_RUNTIME.is_file():+ return FrameInterpolationCapabilities(+ False, gpu_name, driver, hags, 0, 1, False, "missing", "", "missing",+ "Missing", f"Signed NVIDIA DLSSG runtime is missing: {DLSSG_RUNTIME}",+ )+ runtime_hash = _sha256(DLSSG_RUNTIME)+ signature_status = _authenticode_status(DLSSG_RUNTIME)+ if runtime_hash != EXPECTED_RUNTIME_SHA256:+ return FrameInterpolationCapabilities(+ False, gpu_name, driver, hags, 0, 1, False, "unknown", runtime_hash,+ "unknown", "Hash mismatch",+ "The staged nvngx_dlssg.dll does not match the pinned NVIDIA 310.7 release.",+ )+ if signature_status != "Valid":+ return FrameInterpolationCapabilities(+ False, gpu_name, driver, hags, 0, 1, False, "310.7.0.0", runtime_hash,+ "unknown", signature_status,+ "Windows did not validate the NVIDIA Authenticode signature on nvngx_dlssg.dll.",+ )+ if not DLSSG_WORKER.is_file() or _sha256(DLSSG_WORKER) != EXPECTED_WORKER_SHA256:+ return FrameInterpolationCapabilities(+ False, gpu_name, driver, hags, 0, 1, False, "310.7.0.0", runtime_hash,+ "unknown", "Worker hash mismatch",+ "The direct D3D12 worker is missing or does not match its source build manifest.",+ )+ try:+ probed = _probe_worker(gpu.get("adapter_luid"))+ generated_max = max(0, int(probed.get("multi_frame_count_max", 0)))+ multiplier = generated_max + 1 if generated_max else 1+ available = bool(probed.get("available", False)) and generated_max >= 1 and hags+ detail = str(probed.get("detail") or "")+ except Exception as exc:+ generated_max = 0+ multiplier = 1+ available = False+ detail = str(exc)+ probed = {}+ return FrameInterpolationCapabilities(+ available=available,+ gpu=gpu_name,+ driver=driver,+ hags_enabled=hags,+ native_generated_frame_max=generated_max,+ native_multiplier=multiplier,+ cascade_available=available and multiplier >= 2,+ runtime_version=str(probed.get("runtime_version") or "310.7.0.0"),+ runtime_sha256=runtime_hash,+ worker_version=str(probed.get("worker_version") or "1"),+ signature_status=f"{signature_status} (NVIDIA; pinned hash)",+ detail=detail,+ gpu_uuid=str(gpu.get("uuid") or ai_gpu_uuid),+ )+++def clear_capability_cache() -> None:+ probe_frame_interpolation_capabilities.cache_clear()diff --git a/src/frame_interpolation/guides.py b/src/frame_interpolation/guides.pynew file mode 100644index 0000000..09f6ac1--- /dev/null+++ b/src/frame_interpolation/guides.py@@ -0,0 +1,63 @@+from __future__ import annotations++from dataclasses import dataclass++import cv2+import numpy as np+++@dataclass(slots=True)+class Guide:+ motion: np.ndarray+ reset: bool+ scene_score: float+ duplicate: bool+ confidence: float+++class DLSSGGuideGenerator:+ """CUDA-free guide estimation; it never creates an image frame."""++ def __init__(self, width: int, height: int, flow_width: int = 640) -> None:+ self.width = width+ self.height = height+ scale = min(1.0, flow_width / max(1, width))+ self.flow_width = max(64, int(round(width * scale / 2) * 2))+ self.flow_height = max(64, int(round(height * scale / 2) * 2))+ self.previous: np.ndarray | None = None+ self.zero = np.zeros((height, width, 2), dtype=np.float16)+ self.flow = cv2.DISOpticalFlow_create(cv2.DISOPTICAL_FLOW_PRESET_MEDIUM)+ self.flow.setUseSpatialPropagation(True)+ self.flow.setFinestScale(1)++ def _gray(self, rgba: np.ndarray) -> np.ndarray:+ gray = cv2.cvtColor(rgba, cv2.COLOR_RGBA2GRAY)+ return cv2.resize(gray, (self.flow_width, self.flow_height), interpolation=cv2.INTER_AREA)++ def process(self, rgba: np.ndarray, *, force_reset: bool = False) -> Guide:+ current = self._gray(rgba)+ if self.previous is None:+ guide = Guide(self.zero, True, 1.0, False, 0.0)+ else:+ difference = cv2.absdiff(current, self.previous)+ score = float(np.mean(difference)) / 255.0+ duplicate = score < 0.0005+ reset = force_reset or score > 0.24+ if reset or duplicate:+ vectors = self.zero+ confidence = 1.0 if duplicate else 0.0+ else:+ calculated = self.flow.calc(current, self.previous, None)+ calculated = cv2.resize(+ calculated, (self.width, self.height), interpolation=cv2.INTER_LINEAR+ )+ calculated[..., 0] *= self.width / self.flow_width+ calculated[..., 1] *= self.height / self.flow_height+ finite = np.isfinite(calculated).all(axis=2)+ confidence = float(np.mean(finite))+ calculated[~finite] = 0+ reset = confidence < 0.98+ vectors = self.zero if reset else np.ascontiguousarray(calculated.astype(np.float16))+ guide = Guide(vectors, reset, score, duplicate, confidence)+ self.previous = current+ return guidediff --git a/src/frame_interpolation/models.py b/src/frame_interpolation/models.pynew file mode 100644index 0000000..200ff27--- /dev/null+++ b/src/frame_interpolation/models.py@@ -0,0 +1,121 @@+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),+ "120": Fraction(120, 1),+}+FPS_CHOICES = tuple(FPS_RATES)+ENGINE_CHOICES = ("Auto", "Native DLSSG", "Cascade")+++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)"+ rename_mode: str = "Auto"+ custom_suffix: str = "_DLSSFG"+ 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+ runtime_sha256: str+ worker_version: str+ 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)+++@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/native.py b/src/frame_interpolation/native.pynew file mode 100644index 0000000..ba53b10--- /dev/null+++ b/src/frame_interpolation/native.py@@ -0,0 +1,182 @@+from __future__ import annotations++import collections+import struct+import subprocess+import threading+from fractions import Fraction++import numpy as np++from ..runtime import Cancelled, JobController+from .capabilities import DLSSG_WORKER, RUNTIME_DIR+++SETUP_MAGIC = 0x31534746+SETUP_OUT_MAGIC = 0x31524746+FRAME_MAGIC = 0x31464746+FRAME_OUT_MAGIC = 0x314F4746+++def _read_exact(stream, size: int) -> bytes:+ data = bytearray()+ while len(data) < size:+ block = stream.read(size - len(data))+ if not block:+ raise RuntimeError("The direct DLSSG worker closed its output unexpectedly.")+ data.extend(block)+ return bytes(data)+++class DirectDLSSGSession:+ """One direct D3D12 NGX DLSSG history and binary stream."""++ def __init__(+ self,+ width: int,+ height: int,+ frame_count: int,+ generated_count: int,+ controller: JobController,+ adapter_luid: str | None = None,+ ) -> None:+ if not DLSSG_WORKER.is_file():+ raise RuntimeError(f"Direct DLSSG worker is missing: {DLSSG_WORKER}")+ self.width = int(width)+ self.height = int(height)+ self.frame_bytes = self.width * self.height * 4+ self.generated_count = int(generated_count)+ self.controller = controller+ self.logs: collections.deque[str] = collections.deque(maxlen=300)+ command = [str(DLSSG_WORKER), "--serve"]+ if adapter_luid:+ command.extend(["--adapter-luid", adapter_luid])+ self.process = subprocess.Popen(+ command,+ cwd=str(RUNTIME_DIR),+ stdin=subprocess.PIPE,+ stdout=subprocess.PIPE,+ stderr=subprocess.PIPE,+ bufsize=0,+ )+ controller.register(self.process)+ assert self.process.stdin is not None+ assert self.process.stdout is not None+ assert self.process.stderr is not None+ self._log_thread = threading.Thread(target=self._read_logs, daemon=True)+ self._log_thread.start()+ self.process.stdin.write(+ struct.pack(+ "<5I",+ SETUP_MAGIC,+ self.width,+ self.height,+ max(1, int(frame_count)),+ self.generated_count,+ )+ )+ self.process.stdin.flush()+ magic, status, maximum, _reserved = struct.unpack(+ "<4I", _read_exact(self.process.stdout, struct.calcsize("<4I"))+ )+ if magic != SETUP_OUT_MAGIC or status:+ self.close()+ raise RuntimeError(+ f"DLSSG session creation failed (status {status}); runtime maximum is "+ f"{maximum + 1}×.\n{self.log_text()}"+ )+ if self.generated_count > maximum:+ self.close()+ raise RuntimeError(+ f"DLSSG worker rejected {self.generated_count} generated frame(s); "+ f"MultiFrameCountMax is {maximum}."+ )+ self._next_index = 0+ self.closed = False++ def _read_logs(self) -> None:+ assert self.process.stderr is not None+ for raw in iter(self.process.stderr.readline, b""):+ self.logs.append(raw.decode("utf-8", "replace").rstrip())++ def log_text(self) -> str:+ return "\n".join(self.logs)++ def process_frame(+ self,+ rgba: np.ndarray,+ motion: np.ndarray,+ timestamp: Fraction,+ *,+ reset: bool,+ ) -> list[np.ndarray]:+ if self.closed:+ raise RuntimeError("DLSSG session is closed.")+ if self.controller.cancel.is_set():+ raise Cancelled("Frame interpolation was cancelled.")+ color = np.ascontiguousarray(rgba, dtype=np.uint8)+ vectors = np.ascontiguousarray(motion, dtype=np.float16)+ if color.shape != (self.height, self.width, 4):+ raise ValueError(f"DLSSG color frame has unexpected shape {color.shape}.")+ if vectors.shape != (self.height, self.width, 2):+ raise ValueError(f"DLSSG motion field has unexpected shape {vectors.shape}.")+ assert self.process.stdin is not None+ assert self.process.stdout is not None+ self.process.stdin.write(+ struct.pack(+ "<4I2q",+ FRAME_MAGIC,+ self._next_index,+ int(reset),+ 0,+ timestamp.numerator,+ timestamp.denominator,+ )+ )+ self.process.stdin.write(memoryview(color).cast("B"))+ self.process.stdin.write(memoryview(vectors).cast("B"))+ self.process.stdin.flush()+ self._next_index += 1+ magic, status, generated, disabled = struct.unpack(+ "<4I", _read_exact(self.process.stdout, struct.calcsize("<4I"))+ )+ if magic != FRAME_OUT_MAGIC or status:+ raise RuntimeError(+ f"DLSSG evaluation failed at input frame {self._next_index - 1} "+ f"(status {status}).\n{self.log_text()}"+ )+ if disabled:+ return []+ return [+ np.frombuffer(_read_exact(self.process.stdout, self.frame_bytes), np.uint8)+ .reshape(self.height, self.width, 4)+ .copy()+ for _ in range(generated)+ ]++ def close(self) -> None:+ if getattr(self, "closed", False):+ return+ self.closed = True+ process = self.process+ try:+ if process.stdin and not process.stdin.closed:+ process.stdin.close()+ except OSError:+ pass+ try:+ process.wait(timeout=20)+ except subprocess.TimeoutExpired:+ process.terminate()+ try:+ process.wait(timeout=5)+ except subprocess.TimeoutExpired:+ process.kill()+ self.controller.unregister(process)+ self._log_thread.join(timeout=1)++ def __enter__(self) -> "DirectDLSSGSession":+ return self++ def __exit__(self, *_args) -> None:+ self.close()diff --git a/src/frame_interpolation/pipeline.py b/src/frame_interpolation/pipeline.pynew file mode 100644index 0000000..7bb8427--- /dev/null+++ b/src/frame_interpolation/pipeline.py@@ -0,0 +1,548 @@+from __future__ import annotations++import json+import math+import os+import shutil+import threading+import time+from contextlib import nullcontext+from dataclasses import asdict, dataclass+from fractions import Fraction+from pathlib import Path+from typing import Callable, Iterable++import av+import numpy as np++from .. import ffmpeg+from ..naming import output_filename, require_available_output, validate_rename+from ..runtime import (+ JOBS,+ LOGS,+ OUTPUTS,+ Cancelled,+ active_job,+ resolve_runtime_ai_gpu,+ rotate_frame,+)+from .capabilities import probe_frame_interpolation_capabilities+from .guides import DLSSGGuideGenerator+from .models import (+ FrameInterpolationBatchResult,+ FrameInterpolationFailure,+ FrameInterpolationOptions,+ FrameInterpolationResult,+ FrameInterpolationSuccess,+)+from .native import DirectDLSSGSession+from .scheduler import choose_interpolation_plan, output_frame_count+++@dataclass(slots=True)+class TimedFrame:+ rgba: np.ndarray+ timestamp: Fraction+ segment: int+ provenance: str+ source_index: int | None = None+++class DLSSGStage:+ def __init__(+ self,+ session: DirectDLSSGSession,+ width: int,+ height: int,+ generated_count: int,+ *,+ detect_source_cuts: bool,+ ) -> None:+ self.session = session+ self.guides = DLSSGGuideGenerator(width, height)+ self.generated_count = generated_count+ self.previous: TimedFrame | None = None+ self.detect_source_cuts = detect_source_cuts+ self.scene_cuts = 0+ self.duplicates = 0++ def push(self, frame: TimedFrame) -> list[TimedFrame]:+ force_reset = self.previous is not None and frame.segment != self.previous.segment+ guide = self.guides.process(frame.rgba, force_reset=force_reset)+ if self.previous is None:+ self.session.process_frame(frame.rgba, guide.motion, frame.timestamp, reset=True)+ self.previous = frame+ return [frame]+ if self.detect_source_cuts and guide.reset and not force_reset:+ frame.segment = self.previous.segment + 1+ force_reset = True+ self.scene_cuts += 1+ if guide.duplicate:+ self.duplicates += 1+ generated = self.session.process_frame(+ frame.rgba,+ guide.motion,+ frame.timestamp,+ reset=force_reset or guide.reset,+ )+ output: list[TimedFrame] = []+ if not (force_reset or guide.reset):+ interval = frame.timestamp - self.previous.timestamp+ for index, rgba in enumerate(generated, start=1):+ output.append(+ TimedFrame(+ rgba,+ self.previous.timestamp+ + interval * Fraction(index, self.generated_count + 1),+ frame.segment,+ "DLSSG",+ None,+ )+ )+ output.append(frame)+ self.previous = frame+ return output+++class NearestTimestampWriter:+ def __init__(self, nut, stream, target_rate: Fraction, output_count: int) -> None:+ self.nut = nut+ self.stream = stream+ self.target_rate = target_rate+ self.output_count = output_count+ self.next_index = 0+ self.previous: TimedFrame | None = None+ self.tie_late = False+ self.copied = 0+ self.generated = 0+ self.max_error = Fraction(0)+ self.selected_real_ids: set[int] = set()++ def _write(self, frame: TimedFrame, ideal: Fraction) -> None:+ video_frame = av.VideoFrame.from_ndarray(frame.rgba, format="rgba")+ video_frame.pts = self.next_index+ video_frame.time_base = Fraction(1, 1) / self.target_rate+ for packet in self.stream.encode(video_frame):+ self.nut.mux(packet)+ error = abs(frame.timestamp - ideal)+ self.max_error = max(self.max_error, error)+ 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:+ selected = current if self.tie_late else self.previous+ self.tie_late = not self.tie_late+ self._write(selected, ideal)+ else:+ break+ self.previous = current++ def finish(self) -> None:+ if self.previous is None:+ raise RuntimeError("The input video contains no decodable frames.")+ while self.next_index < self.output_count:+ ideal = Fraction(self.next_index, 1) / self.target_rate+ # A finite video has no future endpoint beyond its final real frame.+ # Extend that endpoint over the final frame-duration without asking a+ # synthesizer to extrapolate beyond known motion.+ endpoint = TimedFrame(+ self.previous.rgba,+ ideal,+ self.previous.segment,+ "Source",+ self.previous.source_index,+ )+ self._write(endpoint, ideal)+ for packet in self.stream.encode():+ self.nut.mux(packet)+++_BATCH_CONTEXT = threading.local()+++def _json_safe(value):+ if isinstance(value, Fraction):+ return str(value)+ if isinstance(value, dict):+ return {key: _json_safe(item) for key, item in value.items()}+ if isinstance(value, (list, tuple)):+ return [_json_safe(item) for item in value]+ return value+++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["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.preview_seconds is not None:+ if not math.isfinite(float(options.preview_seconds)) or float(options.preview_seconds) <= 0:+ raise ValueError("Preview duration must be positive.")+++def interpolate_video(+ input_path: str | os.PathLike[str],+ options: FrameInterpolationOptions | None = None,+ progress: Callable[[float, str], None] | None = None,+) -> FrameInterpolationResult:+ from ..prepare import prepare_runtime++ options = options or FrameInterpolationOptions()+ _validate(options)+ source = Path(input_path).resolve()+ if not source.is_file():+ raise FileNotFoundError(source)+ prepared_runtime = prepare_runtime()+ ai_gpu = resolve_runtime_ai_gpu(+ prepared_runtime.gpus, prepared_runtime.runtime_bundle, options.ai_gpu_uuid+ )+ capabilities = probe_frame_interpolation_capabilities(options.ai_gpu_uuid)+ 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()+ with job_context as controller:+ assert controller is not None+ started = time.perf_counter()+ timings: dict[str, float] = {}+ output: Path | None = None+ job_dir: Path | None = None+ sessions: list[DirectDLSSGSession] = []+ encoder = None+ try:+ probe_started = time.perf_counter()+ metadata = ffmpeg.probe_video(source, count_mode="metadata")+ if metadata["hdr"]:+ raise ValueError(+ "Frame Interpolation v1 accepts SDR video only. Convert PQ/HLG input to SDR "+ "before using DLSSG."+ )+ source_rate = Fraction(metadata["rate"])+ cfr = bool(metadata.get("cfr", True))+ frames = int(metadata["frames"])+ if frames <= 0:+ frames = int(ffmpeg.probe_video(source, count_mode="exact")["frames"])+ full_duration = _duration_fraction(+ metadata, source_rate, frames, cfr=cfr+ )+ duration = full_duration+ if options.preview_seconds is not None:+ duration = min(duration, Fraction(str(options.preview_seconds)))+ frames = min(frames, ffmpeg.preview_frame_count(source, float(duration)))+ duration = min(duration, Fraction(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_started+ if progress:+ progress(0.01, f"{plan.path}: {source_rate} → {options.target_rate} FPS")++ OUTPUTS.mkdir(exist_ok=True)+ JOBS.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}"+ job_dir = JOBS / f"{source.stem}-DLSSFG-{stamp}-{os.getpid()}"+ job_dir.mkdir(parents=True, exist_ok=False)+ extension = {"MP4": ".mp4", "MKV": ".mkv", "MOV": ".mov"}[options.container]+ auto_stem = f"{source.stem}_{'DLSSFG_PREVIEW' if options.preview_seconds else 'DLSSFG'}_{stamp}"+ output = OUTPUTS / output_filename(+ source, extension, options.rename_mode, options.custom_suffix, auto_stem+ )+ require_available_output(output)+ # NUT preserves the exact rational frame clock between PyAV and FFmpeg;+ # Matroska's millisecond timestamp scale rounds 60000/1001 and short previews.+ temp_video = job_dir / "interpolated-video.nut"+ selected_codec = "H.264" if options.preview_seconds else options.codec+ video_gpu = ffmpeg.resolve_video_gpu(+ prepared_runtime.gpus,+ options.video_gpu_uuid,+ selected_codec,+ int(metadata["width"]),+ int(metadata["height"]),+ )+ encoder, encoder_thread, encoder_logs, selected_encoder, quality = ffmpeg.start_encoder(+ temp_video,+ selected_codec,+ options.quality,+ controller,+ int(metadata["width"]),+ int(metadata["height"]),+ float(options.target_rate),+ None if video_gpu is None else int(video_gpu["cuda_ordinal"]),+ video_gpu is not None,+ )+ assert encoder.stdin is not None+ if plan.path == "Native DLSSG":+ sessions.append(+ DirectDLSSGSession(+ int(metadata["width"]), int(metadata["height"]), frames,+ plan.generated_per_interval, controller, ai_gpu.get("adapter_luid"),+ )+ )+ elif plan.path == "Cascade":+ for stage_index in range(plan.cascade_stages):+ expected = max(1, (frames - 1) * (1 << stage_index) + 1)+ sessions.append(+ DirectDLSSGSession(+ int(metadata["width"]), int(metadata["height"]), expected, 1, controller+ , ai_gpu.get("adapter_luid")+ )+ )+ stages = [+ DLSSGStage(+ session,+ int(metadata["width"]),+ int(metadata["height"]),+ plan.generated_per_interval if plan.path == "Native DLSSG" else 1,+ detect_source_cuts=index == 0,+ )+ for index, session in enumerate(sessions)+ ]+ nut = av.open(encoder.stdin, mode="w", format="nut")+ raw_stream = nut.add_stream("rawvideo", rate=options.target_rate)+ raw_stream.width = int(metadata["width"])+ raw_stream.height = int(metadata["height"])+ raw_stream.pix_fmt = "rgba"+ raw_stream.time_base = Fraction(1, 1) / options.target_rate+ writer = NearestTimestampWriter(nut, raw_stream, options.target_rate, output_count)++ decoded = 0+ segment = 0+ discontinuities = 0+ last_timestamp: Fraction | None = None+ nominal_interval = Fraction(1, 1) / source_rate+ container = av.open(str(source))+ try:+ stream = container.streams.video[0]+ stream.thread_type = "AUTO"+ for frame in container.decode(stream):+ if decoded >= frames:+ break+ if controller.cancel.is_set():+ raise Cancelled("Frame interpolation stopped by user.")+ timestamp = (+ Fraction(frame.pts) * Fraction(stream.time_base)+ if frame.pts is not None and stream.time_base is not None+ else Fraction(decoded, 1) / source_rate+ )+ if last_timestamp is not None and (+ timestamp <= last_timestamp or timestamp - last_timestamp > nominal_interval * 2+ ):+ segment += 1+ discontinuities += 1+ last_timestamp = timestamp+ rgba = rotate_frame(frame.to_ndarray(format="rgba"), int(metadata["rotation"]))+ timed = TimedFrame(+ np.ascontiguousarray(rgba), timestamp, segment, "Source", decoded+ )+ items = [timed]+ for stage in stages:+ next_items: list[TimedFrame] = []+ for item in items:+ next_items.extend(stage.push(item))+ items = next_items+ for item in items:+ writer.push(item)+ decoded += 1+ if progress and decoded % max(1, frames // 100) == 0:+ progress(0.04 + 0.82 * decoded / frames, f"DLSSG source frame {decoded}/{frames}")+ finally:+ container.close()+ writer.finish()+ nut.close()+ encoder.stdin.close()+ for session in sessions:+ session.close()+ sessions.clear()+ encoder_code = encoder.wait(timeout=180)+ encoder_thread.join(timeout=2)+ controller.unregister(encoder)+ if encoder_code:+ raise RuntimeError("Video encoder failed:\n" + "\n".join(encoder_logs[-40:]))+ if progress:+ progress(0.9, "Muxing original audio, subtitles, chapters, and metadata")+ ffmpeg.final_mux(+ temp_video,+ source,+ output,+ options.container,+ controller,+ preserve_supported_subtitles=True,+ )+ verified = ffmpeg.probe_video(output, count_mode="packets")+ if int(verified["frames"]) != output_count:+ verified = ffmpeg.probe_video(output, count_mode="exact")+ if int(verified["frames"]) != output_count:+ raise RuntimeError(+ f"Output verification found {verified['frames']} frames; expected {output_count}."+ )+ if Fraction(verified["rate"]) != options.target_rate:+ raise RuntimeError(+ f"Output verification found {verified['rate']} FPS; expected {options.target_rate}."+ )+ scene_cuts = sum(stage.scene_cuts for stage in stages)+ duplicate_intervals = sum(stage.duplicates for stage in stages)+ dropped_frames = max(0, decoded - len(writer.selected_real_ids))+ elapsed = time.perf_counter() - started+ report = {+ "status": "success",+ "input": str(source),+ "output": str(output),+ "options": _json_safe(asdict(options)),+ "capabilities": asdict(capabilities),+ "ai_gpu": ai_gpu,+ "video_gpu": video_gpu,+ "plan": {key: str(value) if isinstance(value, Fraction) else value for key, value in asdict(plan).items()},+ "input_frames": decoded,+ "output_frames": output_count,+ "copied_frames": writer.copied,+ "generated_frames": writer.generated,+ "dropped_frames": dropped_frames,+ "maximum_temporal_approximation_seconds": float(writer.max_error),+ "scene_cuts": scene_cuts,+ "duplicate_intervals": duplicate_intervals,+ "timestamp_discontinuities": discontinuities,+ "encoder": selected_encoder,+ "encoding_quality": quality,+ "elapsed_seconds": elapsed,+ }+ report_path = LOGS / f"DLSSFG_{source.stem}_{stamp}.report.json"+ report_path.write_text(json.dumps(report, indent=2), encoding="utf-8")+ if progress:+ progress(1.0, "Frame interpolation complete")+ return FrameInterpolationResult(+ output_path=str(output.resolve()),+ report_path=str(report_path.resolve()),+ 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_frames,+ output_frames=output_count,+ maximum_temporal_approximation_seconds=float(writer.max_error),+ scene_cuts=scene_cuts,+ elapsed_seconds=elapsed,+ timings=timings,+ )+ except Exception as exc:+ if output and output.exists():+ output.unlink()+ if controller.cancel.is_set():+ raise Cancelled("Frame interpolation stopped by user.") from exc+ if isinstance(exc, Cancelled):+ raise+ LOGS.mkdir(exist_ok=True)+ failure_stamp = time.strftime("%Y%m%d-%H%M%S") + f"-{time.time_ns() % 1_000_000:06d}"+ failure_path = LOGS / f"DLSSFG_{source.stem}_{failure_stamp}.failure.json"+ failure_path.write_text(+ json.dumps(+ {+ "status": "failure",+ "input": str(source),+ "options": _json_safe(asdict(options)),+ "error": str(exc),+ "capabilities": asdict(capabilities),+ "worker_logs": [session.log_text() for session in sessions],+ },+ indent=2,+ ),+ encoding="utf-8",+ )+ raise RuntimeError(f"{exc}\nDiagnostic report: {failure_path.resolve()}") from exc+ finally:+ for session in sessions:+ session.close()+ if encoder is not None and encoder.poll() is None:+ encoder.terminate()+ if job_dir and job_dir.exists():+ shutil.rmtree(job_dir, ignore_errors=True)+++def interpolate_videos(+ input_paths: Iterable[str | os.PathLike[str]],+ options: FrameInterpolationOptions | None = None,+ progress: Callable[[float, str], None] | None = None,+) -> FrameInterpolationBatchResult:+ options = options or FrameInterpolationOptions()+ paths = [Path(path).resolve() for path in input_paths]+ if not paths:+ raise ValueError("Choose at least one video.")+ stamp = time.strftime("%Y%m%d-%H%M%S") + f"-{time.time_ns() % 1_000_000:06d}"+ successes: list[FrameInterpolationSuccess] = []+ failures: list[FrameInterpolationFailure] = []+ cancelled = False+ with active_job() as controller:+ _BATCH_CONTEXT.controller = controller+ try:+ for index, path in enumerate(paths):+ if controller.cancel.is_set():+ cancelled = True+ failures.extend(+ FrameInterpolationFailure(i, str(item), "Cancelled before rendering.", True)+ for i, item in enumerate(paths[index:], start=index)+ )+ break+ def item_progress(value: float, message: str, *, position=index) -> None:+ if progress:+ progress((position + value) / len(paths), f"[{position + 1}/{len(paths)}] {message}")+ try:+ result = interpolate_video(path, options, item_progress)+ successes.append(FrameInterpolationSuccess(index, str(path), result))+ except Cancelled as exc:+ cancelled = True+ failures.append(FrameInterpolationFailure(index, str(path), str(exc), True))+ failures.extend(+ FrameInterpolationFailure(+ queued_index,+ str(queued),+ "Cancelled before rendering.",+ True,+ )+ for queued_index, queued in enumerate(+ paths[index + 1 :], start=index + 1+ )+ )+ break+ except Exception as exc:+ failures.append(FrameInterpolationFailure(index, str(path), str(exc)))+ finally:+ del _BATCH_CONTEXT.controller+ manifest = {+ "status": "cancelled" if cancelled else ("partial" if failures else "success"),+ "options": _json_safe(asdict(options)),+ "successes": [asdict(item) for item in successes],+ "failures": [asdict(item) for item in failures],+ }+ LOGS.mkdir(exist_ok=True)+ manifest_path = LOGS / f"DLSSFG_BATCH_{stamp}.manifest.json"+ manifest_path.write_text(json.dumps(manifest, indent=2), encoding="utf-8")+ return FrameInterpolationBatchResult(successes, failures, cancelled, str(manifest_path.resolve()))diff --git a/src/frame_interpolation/scheduler.py b/src/frame_interpolation/scheduler.pynew file mode 100644index 0000000..126c786--- /dev/null+++ b/src/frame_interpolation/scheduler.py@@ -0,0 +1,160 @@+from __future__ import annotations++from dataclasses import dataclass+from fractions import Fraction++from .models import ENGINE_CHOICES, InterpolationPlan+++MAX_OUTPUT_MULTIPLIER = Fraction(6, 1)+++def output_frame_count(duration: Fraction, target_rate: Fraction) -> int:+ """Count timestamps n/rate in the half-open interval [0, duration)."""+ if duration <= 0 or target_rate <= 0:+ return 0+ value = duration * target_rate+ return (value.numerator + value.denominator - 1) // value.denominator+++def exact_native_multiplier(+ source_rate: Fraction, target_rate: Fraction, native_multiplier_max: int+) -> int | None:+ if target_rate <= source_rate:+ return 1+ ratio = target_rate / source_rate+ if ratio.denominator != 1:+ return None+ multiplier = ratio.numerator+ return multiplier if 2 <= multiplier <= native_multiplier_max else None+++def choose_interpolation_plan(+ source_rate: Fraction,+ target_rate: Fraction,+ engine: str,+ native_multiplier_max: int,+ *,+ cfr: bool = True,+) -> InterpolationPlan:+ # Migrate callers and saved settings from the feature's original display name.+ if engine == "Experimental Cascade":+ engine = "Cascade"+ if engine not in ENGINE_CHOICES:+ raise ValueError(f"Unknown DLSS engine {engine!r}.")+ if source_rate <= 0 or target_rate <= 0:+ raise ValueError("Source and output FPS must be positive.")+ ratio = target_rate / source_rate+ if ratio > MAX_OUTPUT_MULTIPLIER:+ raise ValueError(+ f"Requested {float(ratio):.3f}× output exceeds the safe 6× limit for this file."+ )+ if target_rate <= source_rate:+ return InterpolationPlan(+ path="Source-frame resampling",+ source_rate=source_rate,+ target_rate=target_rate,+ native_multiplier=1,+ grid_multiplier=1,+ cascade_stages=0,+ maximum_temporal_error=Fraction(1, 2) / source_rate,+ generated_per_interval=0,+ )++ native_exact = exact_native_multiplier(source_rate, target_rate, native_multiplier_max)+ if engine == "Native DLSSG":+ if not cfr:+ raise ValueError(+ "Native DLSSG requires constant-frame-rate input. Choose Auto or Cascade so "+ "the file can be placed on a deterministic CFR timeline."+ )+ if native_exact is None:+ raise ValueError(+ f"{source_rate} → {target_rate} is not an exact native DLSSG grid supported by "+ f"this runtime (native maximum {native_multiplier_max}×). Choose Auto or Cascade."+ )+ native = native_exact if cfr else None+ if native is not None and engine in {"Auto", "Native DLSSG"}:+ return InterpolationPlan(+ path="Native DLSSG",+ source_rate=source_rate,+ target_rate=target_rate,+ native_multiplier=native,+ grid_multiplier=native,+ cascade_stages=0,+ maximum_temporal_error=Fraction(0),+ generated_per_interval=native - 1,+ )++ if ratio == 2:+ stages = 1+ elif ratio == 4:+ stages = 2+ else:+ stages = 3+ grid = 1 << stages+ exact_dyadic = cfr and ratio in {Fraction(2), Fraction(4)}+ return InterpolationPlan(+ path="Cascade",+ source_rate=source_rate,+ target_rate=target_rate,+ native_multiplier=2,+ grid_multiplier=grid,+ cascade_stages=stages,+ maximum_temporal_error=(+ Fraction(0)+ if exact_dyadic+ else Fraction(1, 2 * grid) / source_rate+ ),+ generated_per_interval=grid - 1,+ )+++@dataclass(frozen=True, slots=True)+class GridSelection:+ source_interval: int+ grid_index: int+ ideal_time: Fraction+ grid_time: Fraction+ error: Fraction+++def select_grid_timestamps(+ duration: Fraction,+ source_rate: Fraction,+ target_rate: Fraction,+ grid_multiplier: int,+) -> list[GridSelection]:+ """Map exact output timestamps to the nearest deterministic DLSSG grid point.++ Exact half-grid ties alternate direction. This prevents a persistent early/late bias,+ while every non-tie remains the mathematically nearest generated instant.+ """+ count = output_frame_count(duration, target_rate)+ selections: list[GridSelection] = []+ tie_late = False+ for output_index in range(count):+ ideal = Fraction(output_index, 1) / target_rate+ grid_position = ideal * source_rate * grid_multiplier+ lower = grid_position.numerator // grid_position.denominator+ remainder = grid_position - lower+ if remainder < Fraction(1, 2):+ nearest = lower+ elif remainder > Fraction(1, 2):+ nearest = lower + 1+ else:+ nearest = lower + int(tie_late)+ tie_late = not tie_late+ interval, grid_index = divmod(nearest, grid_multiplier)+ grid_time = Fraction(nearest, grid_multiplier) / source_rate+ selections.append(+ GridSelection(interval, grid_index, ideal, grid_time, grid_time - ideal)+ )+ return selections+++def is_cfr_timeline(timestamps: list[Fraction], rate: Fraction) -> bool:+ if len(timestamps) < 3:+ return True+ expected = Fraction(1, 1) / rate+ return all(b - a == expected for a, b in zip(timestamps, timestamps[1:]))diff --git a/src/images.py b/src/images.pyindex 1bfe18c..c613622 100644--- a/src/images.py+++ b/src/images.py@@ -28,6 +28,7 @@ from .runtime import (DLSSFrameSession,active_job,resize_fit,+ resolve_runtime_ai_gpu,validate_gpu_runtime,verify_feature_18,write_failure_report,@@ -60,6 +61,7 @@ RAW_EXTENSIONS = {@dataclass(slots=True)class ImageConversionOptions:+ ai_gpu_uuid: str = "auto"nr_style: str = "Default"nr_intensity: float = 1.0local_tone_strength: float = 1.0@@ -78,6 +80,7 @@ class ImageConversionOptions:def neural_options(self) -> ConversionOptions:return ConversionOptions(+ ai_gpu_uuid=self.ai_gpu_uuid,nr_preset=self.nr_preset,nr_style=self.nr_style,nr_intensity=self.nr_intensity,@@ -613,7 +616,9 @@ def convert_images(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 = dict(prepared_runtime.gpu)+ gpu = resolve_runtime_ai_gpu(+ prepared_runtime.gpus, prepared_runtime.runtime_bundle, options.ai_gpu_uuid+ )runtime_bundle = prepared_runtime.runtime_bundletry:validate_gpu_runtime(gpu, runtime_bundle)diff --git a/src/prepare.py b/src/prepare.pyindex eb74d0d..0674ac7 100644--- a/src/prepare.py+++ b/src/prepare.py@@ -15,9 +15,9 @@ from .runtime import (NEURAL_RUNTIME,RUNTIME,WORKER,- detect_gpu,+ detect_gpus,inspect_runtime_bundle,- validate_gpu_runtime,+ resolve_runtime_ai_gpu,validate_runtime_files,)@@ -27,6 +27,7 @@ class PreparedRuntime:"""Reusable, source-independent state prepared once for this process."""gpu: dict[str, Any]+ gpus: tuple[dict[str, Any], ...]runtime_bundle: dict[str, Any]encoder_inventory: dict[str, bool]warmed_files: tuple[str, ...]@@ -89,9 +90,9 @@ def prepare_runtime() -> PreparedRuntime:return _PREPAREDvalidate_runtime_files()- gpu = detect_gpu()+ gpus = detect_gpus()runtime_bundle = inspect_runtime_bundle()- validate_gpu_runtime(gpu, runtime_bundle)+ gpu = resolve_runtime_ai_gpu(gpus, runtime_bundle)inventory = _encoder_inventory()# Initialize Pillow's reusable sRGB profile and optional image backends.@@ -121,6 +122,7 @@ def prepare_runtime() -> PreparedRuntime:_PREPARED = PreparedRuntime(gpu=dict(gpu),+ gpus=tuple(dict(device) for device in gpus),runtime_bundle=runtime_bundle,encoder_inventory=inventory,warmed_files=tuple(str(path.resolve()) for path in paths),diff --git a/src/runtime.py b/src/runtime.pyindex 40d98ac..a18c8d2 100644--- a/src/runtime.py+++ b/src/runtime.py@@ -2,6 +2,7 @@ from __future__ import annotationsimport hashlibimport json+import ctypesimport reimport structimport subprocess@@ -371,11 +372,101 @@ def rotate_frame(frame: np.ndarray, rotation: int) -> np.ndarray:return frame+_RTX_ARCHITECTURES: dict[tuple[int, int], tuple[str, int]] = {+ (8, 0): ("Ampere", 30),+ (8, 6): ("Ampere", 30),+ (8, 7): ("Ampere", 30),+ (8, 8): ("Ampere", 30),+ (8, 9): ("Ada", 40),+ (10, 0): ("Blackwell", 50),+ (10, 3): ("Blackwell", 50),+ (11, 0): ("Blackwell", 50),+ (12, 0): ("Blackwell", 50),+ (12, 1): ("Blackwell", 50),+}+++def _classify_rtx_architecture(name: str, capability: str) -> tuple[str, int]:+ match = re.fullmatch(r"(\d+)\.(\d+)", capability.strip())+ if match is None:+ raise RuntimeError(+ f"{name} reported malformed compute capability {capability!r}; "+ "a current NVIDIA driver is required."+ )+ compute_capability = (int(match.group(1)), int(match.group(2)))+ classified = _RTX_ARCHITECTURES.get(compute_capability)+ if classified is None:+ raise RuntimeError(+ f"{name} (compute capability {capability}) is not a supported RTX architecture. "+ "This build supports Ampere, Ada, and Blackwell RTX GPUs only."+ )+ return classified+++def _normalize_pci_bus_id(value: str) -> str:+ match = re.fullmatch(+ r"(?:([0-9A-Fa-f]{4,8}):)?([0-9A-Fa-f]{2}):([0-9A-Fa-f]{2})\.([0-7])",+ value.strip(),+ )+ if match is None:+ return value.strip().upper()+ domain = int(match.group(1) or "0", 16)+ return f"{domain:04X}:{match.group(2).upper()}:{match.group(3).upper()}.{match.group(4)}"+++def _cuda_device_identities() -> dict[str, dict[str, Any]]:+ """Map normalized PCI bus IDs to the CUDA ordinal and Windows DXGI LUID."""+ try:+ loader = getattr(ctypes, "WinDLL", ctypes.CDLL)+ cuda = loader("nvcuda.dll")+ except (AttributeError, OSError):+ return {}++ c_int_p = ctypes.POINTER(ctypes.c_int)+ cuda.cuInit.argtypes = [ctypes.c_uint]+ cuda.cuInit.restype = ctypes.c_int+ cuda.cuDeviceGetCount.argtypes = [c_int_p]+ cuda.cuDeviceGetCount.restype = ctypes.c_int+ cuda.cuDeviceGet.argtypes = [c_int_p, ctypes.c_int]+ cuda.cuDeviceGet.restype = ctypes.c_int+ cuda.cuDeviceGetPCIBusId.argtypes = [ctypes.c_char_p, ctypes.c_int, ctypes.c_int]+ cuda.cuDeviceGetPCIBusId.restype = ctypes.c_int+ get_luid = getattr(cuda, "cuDeviceGetLuid", None)+ if get_luid is not None:+ get_luid.argtypes = [ctypes.c_void_p, ctypes.POINTER(ctypes.c_uint), ctypes.c_int]+ get_luid.restype = ctypes.c_int++ if cuda.cuInit(0) != 0:+ return {}+ count = ctypes.c_int()+ if cuda.cuDeviceGetCount(ctypes.byref(count)) != 0:+ return {}+ identities: dict[str, dict[str, Any]] = {}+ for ordinal in range(max(0, count.value)):+ device = ctypes.c_int()+ if cuda.cuDeviceGet(ctypes.byref(device), ordinal) != 0:+ continue+ bus_buffer = ctypes.create_string_buffer(32)+ if cuda.cuDeviceGetPCIBusId(bus_buffer, len(bus_buffer), device.value) != 0:+ continue+ luid_hex: str | None = None+ if get_luid is not None:+ luid = (ctypes.c_ubyte * 8)()+ node_mask = ctypes.c_uint()+ if get_luid(luid, ctypes.byref(node_mask), device.value) == 0:+ luid_hex = bytes(luid).hex()+ identities[_normalize_pci_bus_id(bus_buffer.value.decode("ascii", "replace"))] = {+ "cuda_ordinal": ordinal,+ "adapter_luid": luid_hex,+ }+ return identities++@lru_cache(maxsize=1)-def detect_gpu() -> dict:+def detect_gpus() -> tuple[dict[str, Any], ...]:command = ["nvidia-smi",- "--query-gpu=name,driver_version,memory.total,compute_cap",+ "--query-gpu=index,uuid,pci.bus_id,name,driver_version,memory.total,compute_cap","--format=csv,noheader,nounits",]try:@@ -384,31 +475,155 @@ def detect_gpu() -> dict:raise RuntimeError("NVIDIA driver tools are unavailable; an RTX GPU and current driver are required.") from exc- candidates = []- for line in result.stdout.splitlines():+ if result.returncode:+ detail = result.stderr.strip() or result.stdout.strip()+ message = "nvidia-smi failed while detecting an RTX GPU"+ raise RuntimeError(f"{message}: {detail}" if detail else f"{message}.")+ cuda_identities = _cuda_device_identities()+ devices: list[dict[str, Any]] = []+ for fallback_index, line in enumerate(result.stdout.splitlines()):parts = [part.strip() for part in line.split(",")]- if len(parts) >= 4 and "RTX" in parts[0].upper():- candidates.append(parts)+ if not parts or not any(parts):+ continue+ # Four-column rows preserve compatibility with isolated detector tests and+ # older nvidia-smi builds; production drivers use the seven-column query.+ if len(parts) == 4:+ legacy_row = True+ name, driver, memory, capability = parts+ index, uuid, pci_bus_id = str(fallback_index), f"index:{fallback_index}", ""+ elif len(parts) == 7:+ legacy_row = False+ index, uuid, pci_bus_id, name, driver, memory, capability = parts+ else:+ name = parts[3] if len(parts) > 3 else parts[0] or "NVIDIA GPU"+ raise RuntimeError(+ f"{name} returned incomplete nvidia-smi data; expected name, driver, "+ "memory, compute capability, UUID, and PCI bus ID."+ )+ if any(not value for value in (name, driver, memory, capability)):+ raise RuntimeError(+ f"{name or 'NVIDIA GPU'} returned incomplete nvidia-smi data; expected name, "+ "driver, memory, and compute capability."+ )+ try:+ memory_mb = int(memory)+ smi_index = int(index)+ except ValueError as exc:+ raise RuntimeError(+ f"{name} reported malformed index or memory capacity through nvidia-smi."+ ) from exc+ normalized_pci = _normalize_pci_bus_id(pci_bus_id) if pci_bus_id else ""+ identity = cuda_identities.get(normalized_pci, {})+ architecture: str | None = None+ generation: int | None = None+ compatibility_error = ""+ if "RTX" in name.upper():+ try:+ architecture, generation = _classify_rtx_architecture(name, capability)+ except RuntimeError as exc:+ compatibility_error = str(exc)+ else:+ compatibility_error = "The device name does not identify an RTX GPU."+ devices.append(+ {+ "index": smi_index,+ "uuid": uuid,+ "pci_bus_id": normalized_pci,+ "name": name,+ "display_name": (+ f"{name} (experimental RTX 30 path; may be very slow)"+ if generation == 30+ else name+ ),+ "driver": driver,+ "memory_mb": memory_mb,+ "compute_capability": capability,+ "architecture": architecture,+ "generation": generation,+ "beta": generation == 30,+ "ai_compatible": generation is not None,+ "compatibility_error": compatibility_error,+ "cuda_ordinal": identity.get("cuda_ordinal")+ if not legacy_row+ else smi_index,+ "adapter_luid": identity.get("adapter_luid"),+ }+ )+ if not devices:+ raise RuntimeError("No NVIDIA GPU was detected.")+ return tuple(devices)+++def gpu_choice_label(gpu: dict[str, Any]) -> str:+ memory_gib = float(gpu.get("memory_mb", 0)) / 1024+ location = gpu.get("pci_bus_id") or f"index {gpu.get('index', '?')}"+ return f"{gpu.get('name', 'NVIDIA GPU')} | {memory_gib:.0f} GB | PCI {location}"+++def resolve_ai_gpu(gpus: tuple[dict[str, Any], ...], gpu_uuid: str = "auto") -> dict[str, Any]:+ compatible = [gpu for gpu in gpus if gpu.get("ai_compatible")]+ if gpu_uuid != "auto":+ selected = next((gpu for gpu in compatible if gpu.get("uuid") == gpu_uuid), None)+ if selected is not None:+ return dict(selected)+ raise RuntimeError("The selected AI Processing GPU is unavailable or incompatible.")+ if not compatible:+ details = "; ".join(+ str(gpu.get("compatibility_error")) for gpu in gpus if gpu.get("compatibility_error")+ )+ message = "No supported NVIDIA RTX GPU was detected."+ raise RuntimeError(f"{message} {details}" if details else message)+ return dict(compatible[0])+++def resolve_runtime_ai_gpu(+ gpus: tuple[dict[str, Any], ...],+ runtime_bundle: dict[str, Any],+ gpu_uuid: str = "auto",+) -> dict[str, Any]:+ """Resolve an AI device and enforce architecture-specific runtime pairing."""+ candidates = [+ gpu+ for gpu in gpus+ if gpu.get("ai_compatible") and gpu.get("adapter_luid")+ ]+ if gpu_uuid != "auto":+ candidates = [gpu for gpu in candidates if gpu.get("uuid") == gpu_uuid]+ if not candidates:+ raise RuntimeError("The selected AI Processing GPU is unavailable or incompatible.")+ errors: list[str] = []+ for candidate in candidates:+ try:+ validate_gpu_runtime(candidate, runtime_bundle)+ except RuntimeError as exc:+ errors.append(str(exc))+ continue+ return dict(candidate)+ if errors:+ raise RuntimeError("No compatible AI Processing GPU/runtime pair is available. " + " ".join(errors))if not candidates:- raise RuntimeError("No supported NVIDIA RTX GPU was detected.")- name, driver, memory, capability = candidates[0]- match = re.search(r"RTX\s+(\d{2})", name.upper())- generation = int(match.group(1)) if match else 0- if generation < 30:- raise RuntimeError(f"{name} is outside the supported RTX 30/40/50 scope.")- return {- "name": name,- "display_name": (- f"{name} (experimental RTX 30 path; may be very slow)"- if generation == 30- else name- ),- "driver": driver,- "memory_mb": int(memory),- "compute_capability": capability,- "generation": generation,- "beta": generation == 30,- }+ raise RuntimeError(+ "No compatible AI Processing GPU could be mapped to a Windows adapter LUID. "+ "Update or reinstall the NVIDIA display driver."+ )+ return resolve_ai_gpu(gpus, gpu_uuid)+++@lru_cache(maxsize=32)+def _detect_gpu_cached(gpu_uuid: str = "auto") -> dict:+ return resolve_ai_gpu(detect_gpus(), gpu_uuid)+++def detect_gpu(gpu_uuid: str = "auto") -> dict:+ return _detect_gpu_cached(gpu_uuid)+++def _clear_gpu_detection_cache() -> None:+ _detect_gpu_cached.cache_clear()+ detect_gpus.cache_clear()+++detect_gpu.cache_clear = _clear_gpu_detection_cache # type: ignore[attr-defined]def validate_runtime_files() -> None:@@ -490,8 +705,11 @@ class DLSSFrameSession: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)+ worker_command = [str(WORKER), "--video"]+ if gpu.get("adapter_luid"):+ worker_command.extend(["--adapter-luid", str(gpu["adapter_luid"])])self.worker = subprocess.Popen(- [str(WORKER), "--video"],+ worker_command,cwd=RUNTIME,stdin=subprocess.PIPE,stdout=subprocess.PIPE,diff --git a/src/settings.py b/src/settings.pyindex 7a554db..2d51b33 100644--- a/src/settings.py+++ b/src/settings.py@@ -1,12 +1,17 @@from __future__ import annotationsimport configparser+import jsonimport mathimport os-from dataclasses import dataclass+import re+import tempfile+from dataclasses import asdict, dataclass, fields, replacefrom pathlib import Path+from typing import Anyfrom .ffmpeg import ENCODING_QUALITIES+from .frame_interpolation.models import ENGINE_CHOICES, FPS_CHOICESfrom .naming import RENAME_MODES, validate_renamefrom .video import (DLSS_MODEL_PRESETS,@@ -23,10 +28,23 @@ CODEC_CHOICES = ("H.264", "HEVC", "AV1", "ProRes Proxy")CONTAINER_CHOICES = ("MP4", "MKV", "MOV")IMAGE_FORMAT_CHOICES = ("PNG", "JPEG", "WebP", "AVIF", "TIFF")CONFIG_SECTION = "Settings"+PRESET_FORMAT = "dlss5-visual-enhancer-settings-preset"+PRESET_SCHEMA_VERSION = 1+MAX_PRESET_BYTES = 1024 * 1024+_WINDOWS_RESERVED_NAMES = {+ "CON",+ "PRN",+ "AUX",+ "NUL",+ *(f"COM{index}" for index in range(1, 10)),+ *(f"LPT{index}" for index in range(1, 10)),+}@dataclass(frozen=True, slots=True)class UISettings:+ ai_gpu_uuid: str = "auto"+ video_gpu_uuid: str = "auto"nr_style: str = "Default"nr_intensity: float = 1.0local_tone_strength: float = 1.0@@ -45,6 +63,13 @@ class UISettings:video_rename_mode: str = "Auto"video_custom_suffix: str = "_DLSS5"dlss_model_preset: str = "Default"+ frame_interpolation_target_fps: str = "60"+ frame_interpolation_engine: str = "Auto"+ frame_interpolation_codec: str = "H.264"+ frame_interpolation_container: str = "MP4"+ frame_interpolation_quality: str = "Auto (Default)"+ frame_interpolation_rename_mode: str = "Auto"+ frame_interpolation_custom_suffix: str = "_DLSSFG"def component_values(self,@@ -69,6 +94,12 @@ DEFAULT_SETTINGS = UISettings()def _validate(settings: UISettings) -> UISettings:+ for label, value in (+ ("AI Processing GPU", settings.ai_gpu_uuid),+ ("Video Processing GPU", settings.video_gpu_uuid),+ ):+ if not isinstance(value, str) or not value.strip() or len(value) > 160:+ raise ValueError(f"{label} selection must be Automatic or a valid GPU UUID.")resolve_native_settings(ConversionOptions(nr_preset=settings.nr_preset,@@ -90,6 +121,26 @@ def _validate(settings: UISettings) -> UISettings:"Container": (settings.container, CONTAINER_CHOICES),"Encoding quality": (settings.quality, QUALITY_CHOICES),"Image format": (settings.image_format, IMAGE_FORMAT_CHOICES),+ "Frame Interpolation FPS": (+ settings.frame_interpolation_target_fps,+ FPS_CHOICES,+ ),+ "Frame Interpolation engine": (+ settings.frame_interpolation_engine,+ ENGINE_CHOICES,+ ),+ "Frame Interpolation codec": (+ settings.frame_interpolation_codec,+ CODEC_CHOICES,+ ),+ "Frame Interpolation container": (+ settings.frame_interpolation_container,+ CONTAINER_CHOICES,+ ),+ "Frame Interpolation quality": (+ settings.frame_interpolation_quality,+ QUALITY_CHOICES,+ ),}for label, (value, choices) in allowed.items():if value not in choices:@@ -100,9 +151,135 @@ def _validate(settings: UISettings) -> UISettings:raise ValueError("Image quality must be an integer from 1 to 100.")validate_rename(settings.image_rename_mode, settings.image_custom_suffix)validate_rename(settings.video_rename_mode, settings.video_custom_suffix)+ validate_rename(+ settings.frame_interpolation_rename_mode,+ settings.frame_interpolation_custom_suffix,+ )return settings+def _preset_name(value: str) -> str:+ if not isinstance(value, str):+ raise ValueError("Preset name must be text.")+ name = value.strip()+ if not name:+ raise ValueError("Enter a preset name before exporting.")+ if len(name) > 120:+ raise ValueError("Preset name must be 120 characters or fewer.")+ if any(ord(character) < 32 for character in name):+ raise ValueError("Preset name cannot contain control characters.")+ return name+++def preset_filename(name: str) -> str:+ """Return a portable JSON filename while preserving the display name in the file."""+ display_name = _preset_name(name)+ characters = [+ character if character.isalnum() or character in "-_" else "_"+ for character in display_name+ ]+ stem = re.sub(r"_+", "_", "".join(characters)).strip("-_")[:80].rstrip("-_")+ if not stem:+ raise ValueError("Preset name must contain at least one letter or number.")+ if stem.upper() in _WINDOWS_RESERVED_NAMES:+ stem += "_preset"+ return f"{stem}.json"+++def preset_document(name: str, settings: UISettings) -> dict[str, Any]:+ """Build the versioned user-facing preset document."""+ display_name = _preset_name(name)+ _validate(settings)+ return {+ "format": PRESET_FORMAT,+ "schema_version": PRESET_SCHEMA_VERSION,+ "name": display_name,+ "settings": asdict(settings),+ }+++def export_settings_preset(name: str, settings: UISettings) -> Path:+ """Write a validated preset to an isolated temporary download directory."""+ document = preset_document(name, settings)+ filename = preset_filename(document["name"])+ directory = Path(tempfile.mkdtemp(prefix="dlss5-settings-preset-"))+ path = directory / filename+ path.write_text(+ json.dumps(document, indent=2, ensure_ascii=False) + "\n",+ encoding="utf-8",+ )+ return path.resolve()+++def _coerce_preset_value(field_name: str, value: Any, current: UISettings) -> Any:+ expected = getattr(current, field_name)+ if isinstance(expected, bool):+ if not isinstance(value, bool):+ raise ValueError(f"Preset setting {field_name!r} must be a boolean.")+ return value+ if isinstance(expected, int):+ if isinstance(value, bool) or not isinstance(value, int):+ raise ValueError(f"Preset setting {field_name!r} must be an integer.")+ return value+ if isinstance(expected, float):+ if isinstance(value, bool) or not isinstance(value, (int, float)):+ raise ValueError(f"Preset setting {field_name!r} must be a number.")+ number = float(value)+ if not math.isfinite(number):+ raise ValueError(f"Preset setting {field_name!r} must be finite.")+ return number+ if isinstance(expected, str):+ if not isinstance(value, str):+ raise ValueError(f"Preset setting {field_name!r} must be text.")+ return value+ raise ValueError(f"Preset setting {field_name!r} has an unsupported type.")+++def import_settings_preset(+ path: str | os.PathLike[str], current: UISettings+) -> tuple[str, UISettings]:+ """Load, compatibly merge, and atomically validate a version-1 preset."""+ preset_path = Path(path)+ if preset_path.suffix.casefold() != ".json":+ raise ValueError("Choose a JSON preset file.")+ try:+ size = preset_path.stat().st_size+ except OSError as exc:+ raise ValueError("The selected preset file cannot be read.") from exc+ if size > MAX_PRESET_BYTES:+ raise ValueError("Preset file is too large; the maximum size is 1 MiB.")+ try:+ document = json.loads(preset_path.read_text(encoding="utf-8"))+ except (OSError, UnicodeError, json.JSONDecodeError) as exc:+ raise ValueError("Preset file is not valid UTF-8 JSON.") from exc+ if not isinstance(document, dict):+ raise ValueError("Preset JSON must contain an object at its top level.")+ if document.get("format") != PRESET_FORMAT:+ raise ValueError("This JSON file is not a DLSS 5 Visual Enhancer settings preset.")+ version = document.get("schema_version")+ if isinstance(version, bool) or not isinstance(version, int):+ raise ValueError("Preset schema_version must be an integer.")+ if version != PRESET_SCHEMA_VERSION:+ direction = "newer" if version > PRESET_SCHEMA_VERSION else "unsupported"+ raise ValueError(+ f"Preset schema version {version} is {direction}; this build supports version "+ f"{PRESET_SCHEMA_VERSION}."+ )+ name = _preset_name(document.get("name"))+ imported = document.get("settings")+ if not isinstance(imported, dict):+ raise ValueError("Preset settings must be a JSON object.")++ known_names = {field.name for field in fields(UISettings)}+ changes = {+ key: _coerce_preset_value(key, value, current)+ for key, value in imported.items()+ if key in known_names+ }+ merged = replace(current, **changes)+ return name, _validate(merged)++def load_settings(path: str | os.PathLike[str]) -> UISettings:config_path = Path(path)parser = configparser.ConfigParser()@@ -142,6 +319,15 @@ def load_settings(path: str | os.PathLike[str]) -> UISettings:parsed = configparser.ConfigParser.BOOLEAN_STATES.get(str(raw_value).casefold())return parsed if parsed is not None else default+ def frame_interpolation_engine() -> str:+ value = section.get(+ "frame_interpolation_engine",+ DEFAULT_SETTINGS.frame_interpolation_engine,+ )+ if value == "Experimental Cascade":+ return "Cascade"+ return value if value in ENGINE_CHOICES else DEFAULT_SETTINGS.frame_interpolation_engine+image_rename_mode = choice("image_rename_mode", RENAME_MODES, DEFAULT_SETTINGS.image_rename_mode)@@ -154,6 +340,15 @@ def load_settings(path: str | os.PathLike[str]) -> UISettings:video_custom_suffix = section.get("video_custom_suffix", DEFAULT_SETTINGS.video_custom_suffix)+ frame_interpolation_rename_mode = choice(+ "frame_interpolation_rename_mode",+ RENAME_MODES,+ DEFAULT_SETTINGS.frame_interpolation_rename_mode,+ )+ frame_interpolation_custom_suffix = section.get(+ "frame_interpolation_custom_suffix",+ DEFAULT_SETTINGS.frame_interpolation_custom_suffix,+ )try:validate_rename(image_rename_mode, image_custom_suffix)except ValueError:@@ -164,8 +359,20 @@ def load_settings(path: str | os.PathLike[str]) -> UISettings:except ValueError:video_rename_mode = DEFAULT_SETTINGS.video_rename_modevideo_custom_suffix = DEFAULT_SETTINGS.video_custom_suffix+ try:+ validate_rename(+ frame_interpolation_rename_mode,+ frame_interpolation_custom_suffix,+ )+ except ValueError:+ frame_interpolation_rename_mode = DEFAULT_SETTINGS.frame_interpolation_rename_mode+ frame_interpolation_custom_suffix = DEFAULT_SETTINGS.frame_interpolation_custom_suffixreturn UISettings(+ ai_gpu_uuid=section.get("ai_gpu_uuid", DEFAULT_SETTINGS.ai_gpu_uuid).strip()+ or DEFAULT_SETTINGS.ai_gpu_uuid,+ video_gpu_uuid=section.get("video_gpu_uuid", DEFAULT_SETTINGS.video_gpu_uuid).strip()+ or DEFAULT_SETTINGS.video_gpu_uuid,nr_preset=choice("nr_preset", tuple(NR_PRESETS), DEFAULT_SETTINGS.nr_preset),nr_style=choice("nr_style", tuple(NR_STYLES), DEFAULT_SETTINGS.nr_style),nr_intensity=number("nr_intensity", 0.0, 2.0, DEFAULT_SETTINGS.nr_intensity),@@ -196,6 +403,29 @@ def load_settings(path: str | os.PathLike[str]) -> UISettings:image_custom_suffix=image_custom_suffix,video_rename_mode=video_rename_mode,video_custom_suffix=video_custom_suffix,+ frame_interpolation_target_fps=choice(+ "frame_interpolation_target_fps",+ FPS_CHOICES,+ DEFAULT_SETTINGS.frame_interpolation_target_fps,+ ),+ frame_interpolation_engine=frame_interpolation_engine(),+ frame_interpolation_codec=choice(+ "frame_interpolation_codec",+ CODEC_CHOICES,+ DEFAULT_SETTINGS.frame_interpolation_codec,+ ),+ frame_interpolation_container=choice(+ "frame_interpolation_container",+ CONTAINER_CHOICES,+ DEFAULT_SETTINGS.frame_interpolation_container,+ ),+ frame_interpolation_quality=choice(+ "frame_interpolation_quality",+ QUALITY_CHOICES,+ DEFAULT_SETTINGS.frame_interpolation_quality,+ ),+ frame_interpolation_rename_mode=frame_interpolation_rename_mode,+ frame_interpolation_custom_suffix=frame_interpolation_custom_suffix,)@@ -205,6 +435,8 @@ def save_settings(path: str | os.PathLike[str], settings: UISettings) -> None:config_path.parent.mkdir(parents=True, exist_ok=True)parser = configparser.ConfigParser()parser[CONFIG_SECTION] = {+ "ai_gpu_uuid": settings.ai_gpu_uuid,+ "video_gpu_uuid": settings.video_gpu_uuid,"nr_preset": settings.nr_preset,"nr_style": settings.nr_style,"nr_intensity": f"{settings.nr_intensity:.2f}",@@ -223,6 +455,13 @@ def save_settings(path: str | os.PathLike[str], settings: UISettings) -> None:"video_rename_mode": settings.video_rename_mode,"video_custom_suffix": settings.video_custom_suffix,"dlss_model_preset": settings.dlss_model_preset,+ "frame_interpolation_target_fps": settings.frame_interpolation_target_fps,+ "frame_interpolation_engine": settings.frame_interpolation_engine,+ "frame_interpolation_codec": settings.frame_interpolation_codec,+ "frame_interpolation_container": settings.frame_interpolation_container,+ "frame_interpolation_quality": settings.frame_interpolation_quality,+ "frame_interpolation_rename_mode": settings.frame_interpolation_rename_mode,+ "frame_interpolation_custom_suffix": settings.frame_interpolation_custom_suffix,}temporary = config_path.with_name(f".{config_path.name}.tmp")diff --git a/src/video.py b/src/video.pyindex 7b59914..a872972 100644--- a/src/video.py+++ b/src/video.py@@ -27,6 +27,7 @@ from .runtime import (DLSSFrameSession,active_job,resize_fit,+ resolve_runtime_ai_gpu,rotate_frame,verify_feature_18,write_failure_report,@@ -42,6 +43,8 @@ validate_codec_container = ffmpeg.validate_codec_container@dataclass(slots=True)class ConversionOptions:+ ai_gpu_uuid: str = "auto"+ video_gpu_uuid: str = "auto"nr_style: str = "Default"nr_intensity: float = 1.0local_tone_strength: float = 1.0@@ -381,7 +384,10 @@ def convert_video(job_dir: Path | None = Noneoutput: Path | None = Nonesession: DLSSFrameSession | None = None- gpu: dict | None = dict(prepared_runtime.gpu)+ gpu: dict | None = resolve_runtime_ai_gpu(+ prepared_runtime.gpus, prepared_runtime.runtime_bundle, options.ai_gpu_uuid+ )+ video_gpu: dict | None = Noneruntime_bundle: dict | None = prepared_runtime.runtime_bundleencoder = Noneencoder_setup_thread: threading.Thread | None = None@@ -419,6 +425,13 @@ def convert_video(output_width, output_height = resolve_output_size(input_width, input_height, factor)+ video_gpu = ffmpeg.resolve_video_gpu(+ prepared_runtime.gpus,+ options.video_gpu_uuid,+ "H.264" if is_preview else options.codec,+ output_width,+ output_height,+ )OUTPUTS.mkdir(exist_ok=True)LOGS.mkdir(exist_ok=True)JOBS.mkdir(exist_ok=True)@@ -467,6 +480,8 @@ def convert_video(output_width,output_height,float(metadata["fps"]),+ None if video_gpu is None else int(video_gpu["cuda_ordinal"]),+ video_gpu is not None,))except BaseException as exc:@@ -762,6 +777,8 @@ def convert_video(for key, value in verified.items()},"gpu": gpu,+ "ai_gpu": gpu,+ "video_gpu": video_gpu,"encoder": selected_encoder,"encoding_quality": encoding_quality,"frames_processed": delivered,